"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import {
  User,
  Mail,
  Phone,
  GraduationCap,
  Building2,
  Calendar,
  Edit3,
  Camera,
  Lock,
  CreditCard,
  Shield,
  Bell,
  Save,
  X,
  Check,
  Eye,
  EyeOff,
  Upload,
  FileCheck,
  Loader2,
  LogOut,
} from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { MembershipCardEngine } from "@/components/cards/membership-card-engine";

interface UserProfile {
  id: string;
  name: string;
  email: string;
  phone: string;
  faculty: string;
  department: string;
  graduationYear: string;
  bio: string;
  image: string | null;
  cardPhoto: string | null;
  graduationCertificate: string | null;
  membershipNumber: string;
  memberStatus: string;
  memberSince: string;
  studentId: string;
}

export default function ProfilePage({ params }: { params: Promise<{ lang: string }> }) {
  const [lang, setLang] = useState("ar");
  const isArabic = lang === "ar";

  const { data: session, status, update } = useSession();
  const router = useRouter();

  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState<"profile" | "card" | "security">("profile");
  const [editing, setEditing] = useState(false);
  const [editForm, setEditForm] = useState<Partial<UserProfile>>({});

  // Password change states
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [resetEmail, setResetEmail] = useState("");
  const [passwordSent, setPasswordSent] = useState(false);
  const [sendingReset, setSendingReset] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [changingPassword, setChangingPassword] = useState(false);
  const [passwordError, setPasswordError] = useState("");
  const [passwordSuccess, setPasswordSuccess] = useState("");

  // Avatar upload
  const [uploadingAvatar, setUploadingAvatar] = useState(false);

  // Card photo upload
  const [uploadingCard, setUploadingCard] = useState(false);

  useEffect(() => {
    params.then((p) => setLang(p.lang));
  }, [params]);

  useEffect(() => {
    if (status === "unauthenticated") {
      router.push("/auth/login");
    }
  }, [status, router]);

  useEffect(() => {
    if (session?.user?.id) {
      fetchProfile();
    }
  }, [session]);

  const fetchProfile = async () => {
    try {
      const res = await fetch("/api/profile");
      if (res.ok) {
        const data = await res.json();
        setProfile(data);
        setEditForm(data);
        setResetEmail(data.email);
      }
    } catch (error) {
      console.error("Failed to fetch profile:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSaveProfile = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editForm),
      });
      if (res.ok) {
        const data = await res.json();
        setProfile(data);
        setEditing(false);
        await update({ name: data.name });
      }
    } catch (error) {
      console.error("Failed to save profile:", error);
    } finally {
      setSaving(false);
    }
  };

  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingAvatar(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });
      if (res.ok) {
        const data = await res.json();
        const imageUrl = data.url || data.imageUrl;
        await fetch("/api/profile", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ image: imageUrl }),
        });
        setProfile((prev) => (prev ? { ...prev, image: imageUrl } : null));
      }
    } catch (error) {
      console.error("Failed to upload avatar:", error);
    } finally {
      setUploadingAvatar(false);
    }
  };

  const handleCardPhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingCard(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });
      if (res.ok) {
        const data = await res.json();
        const imageUrl = data.url || data.imageUrl;
        await fetch("/api/profile", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ cardPhoto: imageUrl }),
        });
        setProfile((prev) => (prev ? { ...prev, cardPhoto: imageUrl } : null));
      }
    } catch (error) {
      console.error("Failed to upload card photo:", error);
    } finally {
      setUploadingCard(false);
    }
  };

  const handleSendResetEmail = async () => {
    if (!resetEmail) return;
    setSendingReset(true);
    try {
      const res = await fetch("/api/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: resetEmail }),
      });
      if (res.ok) {
        setPasswordSent(true);
      }
    } catch (error) {
      console.error("Failed to send reset email:", error);
    } finally {
      setSendingReset(false);
    }
  };

  const handleChangePassword = async () => {
    setPasswordError("");
    setPasswordSuccess("");

    if (!currentPassword || !newPassword) {
      setPasswordError(isArabic ? "املأ جميع الحقول" : "Fill all fields");
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordError(isArabic ? "كلمتا المرور غير متطابقتين" : "Passwords do not match");
      return;
    }
    if (newPassword.length < 8) {
      setPasswordError(isArabic ? "كلمة المرور يجب أن تكون 8 أحرف على الأقل" : "Password must be at least 8 characters");
      return;
    }

    setChangingPassword(true);
    try {
      const res = await fetch("/api/profile/password", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const data = await res.json();
      if (res.ok) {
        setPasswordSuccess(isArabic ? "تم تغيير كلمة المرور بنجاح" : "Password changed successfully");
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
      } else {
        setPasswordError(data.error || (isArabic ? "حدث خطأ" : "An error occurred"));
      }
    } catch {
      setPasswordError(isArabic ? "حدث خطأ في الاتصال" : "Connection error");
    } finally {
      setChangingPassword(false);
    }
  };

  const tabs = [
    { id: "profile" as const, label: isArabic ? "الملف الشخصي" : "Profile", icon: User },
    { id: "card" as const, label: isArabic ? "بطاقة العضوية" : "Membership Card", icon: CreditCard },
    { id: "security" as const, label: isArabic ? "الأمان" : "Security", icon: Shield },
  ];

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p className="text-text-secondary">
          {isArabic ? "حدث خطأ في تحميل البيانات" : "Error loading profile"}
        </p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background py-8">
      <div className="container mx-auto px-4 max-w-6xl">
        {/* Profile Header */}
        <div className="bg-gradient-to-br from-primary to-primary-dark rounded-2xl p-8 mb-8 text-white">
          <div className="flex flex-col md:flex-row items-center gap-6">
            <div className="relative group">
              <Avatar
                src={profile.image}
                fallback={profile.name}
                size="xl"
                className="w-24 h-24 text-3xl border-4 border-white/30"
              />
              <label className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
                <Camera className="w-6 h-6 text-white" />
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={handleAvatarUpload}
                  disabled={uploadingAvatar}
                />
              </label>
              {uploadingAvatar && (
                <div className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center">
                  <Loader2 className="w-6 h-6 text-white animate-spin" />
                </div>
              )}
            </div>

            <div className="text-center md:text-right flex-1">
              <h1 className="text-2xl font-bold mb-2">{profile.name}</h1>
              <p className="text-white/80 mb-1">{profile.email}</p>
              <p className="text-white/60 text-sm">
                {isArabic ? "عضو منذ" : "Member since"} {profile.memberSince}
              </p>
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="border-white/30 text-white hover:bg-white/10"
                onClick={() => router.push("/")}
              >
                <LogOut className="w-4 h-4 ml-2" />
                {isArabic ? "العودة للرئيسية" : "Back to Home"}
              </Button>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-2 mb-8 overflow-x-auto pb-2">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-6 py-3 rounded-xl font-medium transition-all whitespace-nowrap ${
                activeTab === tab.id
                  ? "bg-primary text-white shadow-lg"
                  : "bg-surface text-text-secondary hover:bg-primary/5"
              }`}
            >
              <tab.icon className="w-5 h-5" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Tab Content */}
        {activeTab === "profile" && (
          <div className="grid lg:grid-cols-3 gap-8">
            <div className="lg:col-span-2">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between">
                  <CardTitle>{isArabic ? "معلومات الشخصية" : "Personal Information"}</CardTitle>
                  {!editing ? (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setEditing(true)}
                    >
                      <Edit3 className="w-4 h-4 ml-2" />
                      {isArabic ? "تعديل" : "Edit"}
                    </Button>
                  ) : (
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setEditing(false);
                          setEditForm(profile);
                        }}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                      <Button
                        size="sm"
                        onClick={handleSaveProfile}
                        disabled={saving}
                      >
                        {saving ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <Save className="w-4 h-4 ml-2" />
                        )}
                        {isArabic ? "حفظ" : "Save"}
                      </Button>
                    </div>
                  )}
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "الاسم الكامل" : "Full Name"}
                      </label>
                      {editing ? (
                        <Input
                          value={editForm.name || ""}
                          onChange={(e) =>
                            setEditForm({ ...editForm, name: e.target.value })
                          }
                        />
                      ) : (
                        <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                          <User className="w-5 h-5 text-text-light" />
                          <span>{profile.name}</span>
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "البريد الإلكتروني" : "Email"}
                      </label>
                      <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                        <Mail className="w-5 h-5 text-text-light" />
                        <span>{profile.email}</span>
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "رقم الهاتف" : "Phone"}
                      </label>
                      {editing ? (
                        <Input
                          value={editForm.phone || ""}
                          onChange={(e) =>
                            setEditForm({ ...editForm, phone: e.target.value })
                          }
                        />
                      ) : (
                        <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                          <Phone className="w-5 h-5 text-text-light" />
                          <span>{profile.phone || "-"}</span>
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "رقم الطالب" : "Student ID"}
                      </label>
                      <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                        <GraduationCap className="w-5 h-5 text-text-light" />
                        <span>{profile.studentId}</span>
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "الكلية" : "Faculty"}
                      </label>
                      {editing ? (
                        <Input
                          value={editForm.faculty || ""}
                          onChange={(e) =>
                            setEditForm({ ...editForm, faculty: e.target.value })
                          }
                        />
                      ) : (
                        <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                          <Building2 className="w-5 h-5 text-text-light" />
                          <span>{profile.faculty || "-"}</span>
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-text-secondary mb-2">
                        {isArabic ? "سنة التخرج" : "Graduation Year"}
                      </label>
                      <div className="flex items-center gap-3 p-3 bg-background rounded-lg">
                        <Calendar className="w-5 h-5 text-text-light" />
                        <span>{profile.graduationYear}</span>
                      </div>
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-text-secondary mb-2">
                      {isArabic ? "نبذة شخصية" : "Bio"}
                    </label>
                    {editing ? (
                      <textarea
                        value={editForm.bio || ""}
                        onChange={(e) =>
                          setEditForm({ ...editForm, bio: e.target.value })
                        }
                        rows={3}
                        className="w-full px-4 py-3 rounded-lg border border-border bg-background text-text focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
                      />
                    ) : (
                      <div className="p-3 bg-background rounded-lg">
                        <p>{profile.bio || (isArabic ? "لم تتم إضافة نبذة بعد" : "No bio added yet")}</p>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Sidebar Stats */}
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>{isArabic ? "الإحصائيات" : "Statistics"}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between p-3 bg-background rounded-lg">
                    <span className="text-text-secondary">
                      {isArabic ? "الفعاليات المشاركة" : "Events Attended"}
                    </span>
                    <span className="font-bold text-primary">12</span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-background rounded-lg">
                    <span className="text-text-secondary">
                      {isArabic ? "الشهادات" : "Certificates"}
                    </span>
                    <span className="font-bold text-primary">5</span>
                  </div>
                  <div className="flex items-center justify-between p-3 bg-background rounded-lg">
                    <span className="text-text-secondary">
                      {isArabic ? "التبرعات" : "Donations"}
                    </span>
                    <span className="font-bold text-primary">3</span>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>{isArabic ? "العضوية" : "Membership"}</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-center p-4 bg-gradient-to-br from-primary/5 to-secondary/5 rounded-xl">
                    <CreditCard className="w-12 h-12 text-primary mx-auto mb-3" />
                    <p className="font-bold text-lg">{profile.memberStatus}</p>
                    <p className="text-text-secondary text-sm mt-1">
                      {profile.membershipNumber}
                    </p>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )}

        {activeTab === "card" && (
          <div className="max-w-lg mx-auto">
            {/* Card Photo Upload */}
            <Card className="mb-6">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Camera className="w-5 h-5" />
                  {isArabic ? "صورة البطاقة" : "Card Photo"}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-4">
                  <div className="relative group">
                    <div className="w-24 h-24 rounded-xl overflow-hidden bg-gradient-to-br from-primary/10 to-secondary/10 flex items-center justify-center border-2 border-dashed border-primary/30">
                      {profile.cardPhoto ? (
                        <img
                          src={profile.cardPhoto}
                          alt="Card Photo"
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <User className="w-10 h-10 text-primary/30" />
                      )}
                    </div>
                    <label className="absolute inset-0 bg-black/50 rounded-xl flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
                      <Camera className="w-5 h-5 text-white" />
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handleCardPhotoUpload}
                        disabled={uploadingCard}
                      />
                    </label>
                    {uploadingCard && (
                      <div className="absolute inset-0 bg-black/50 rounded-xl flex items-center justify-center">
                        <Loader2 className="w-5 h-5 text-white animate-spin" />
                      </div>
                    )}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm text-text-secondary mb-2">
                      {isArabic
                        ? "أضف صورة شخصية لتظهر على البطاقة"
                        : "Add a personal photo to appear on the card"}
                    </p>
                    <label className="inline-flex items-center gap-2 px-4 py-2 bg-primary/10 text-primary rounded-lg cursor-pointer hover:bg-primary/20 transition-colors text-sm font-medium">
                      <Camera className="w-4 h-4" />
                      {profile.cardPhoto
                        ? isArabic ? "تغيير الصورة" : "Change Photo"
                        : isArabic ? "إضافة صورة" : "Add Photo"}
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handleCardPhotoUpload}
                        disabled={uploadingCard}
                      />
                    </label>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Graduation Certificate Upload */}
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 rounded-xl bg-primary/10 flex items-center justify-center shrink-0">
                    {profile.graduationCertificate ? (
                      <FileCheck className="w-8 h-8 text-green-600" />
                    ) : (
                      <GraduationCap className="w-8 h-8 text-primary" />
                    )}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm text-text-secondary mb-2">
                      {isArabic
                        ? "أضف شهادة التخرج للتحقق من الهوية"
                        : "Add graduation certificate for identity verification"}
                    </p>
                    <label className="inline-flex items-center gap-2 px-4 py-2 bg-primary/10 text-primary rounded-lg cursor-pointer hover:bg-primary/20 transition-colors text-sm font-medium">
                      {profile.graduationCertificate ? (
                        <>
                          <Check className="w-4 h-4 text-green-600" />
                          <span className="text-green-600">{isArabic ? "تم الرفع" : "Uploaded"}</span>
                        </>
                      ) : (
                        <>
                          <Upload className="w-4 h-4" />
                          {isArabic ? "رفع الشهادة" : "Upload Certificate"}
                        </>
                      )}
                      <input
                        type="file"
                        accept="image/jpeg,image/png,image/webp,application/pdf"
                        className="hidden"
                        onChange={async (e) => {
                          const file = e.target.files?.[0]
                          if (!file) return
                          if (file.size > 5 * 1024 * 1024) {
                            alert(isArabic ? "حجم الملف يجب أن يكون أقل من 5 ميجابايت" : "File size must be less than 5MB")
                            return
                          }
                          const formData = new FormData()
                          formData.append("file", file)
                          formData.append("folder", "members")
                          try {
                            const res = await fetch("/api/upload", { method: "POST", body: formData })
                            const data = await res.json()
                            if (!res.ok) throw new Error(data.error)
                            await fetch("/api/profile", {
                              method: "PATCH",
                              headers: { "Content-Type": "application/json" },
                              body: JSON.stringify({ graduationCertificate: data.url }),
                            })
                            setProfile((prev) => prev ? { ...prev, graduationCertificate: data.url } : null)
                          } catch {
                            alert(isArabic ? "فشل رفع الملف" : "Failed to upload file")
                          }
                        }}
                      />
                    </label>
                  </div>
                </div>
                {profile.graduationCertificate && (
                  <div className="mt-3 p-3 bg-gray-50 rounded-lg flex items-center justify-between">
                    <a href={profile.graduationCertificate} target="_blank" rel="noopener noreferrer" className="text-sm text-primary hover:underline truncate">
                      {isArabic ? "عرض الشهادة" : "View Certificate"}
                    </a>
                    <button
                      onClick={async () => {
                        await fetch("/api/profile", {
                          method: "PATCH",
                          headers: { "Content-Type": "application/json" },
                          body: JSON.stringify({ graduationCertificate: "" }),
                        })
                        setProfile((prev) => prev ? { ...prev, graduationCertificate: "" } : null)
                      }}
                      className="text-sm text-red-500 hover:text-red-700"
                    >
                      {isArabic ? "حذف" : "Delete"}
                    </button>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Unified Membership Card - Template Engine */}
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 flex justify-center">
              <MembershipCardEngine
                member={{
                  id: profile.id,
                  nameAr: profile.name,
                  nameEn: profile.name,
                  membershipNumber: profile.membershipNumber,
                  memberType: profile.memberStatus,
                  photo: profile.cardPhoto || profile.image || undefined,
                  specialization: profile.faculty || undefined,
                  department: profile.department || undefined,
                  graduationYear: parseInt(profile.graduationYear) || undefined,
                  phone: profile.phone,
                  email: profile.email,
                }}
                showDownload
                showBoth
                size="lg"
              />
            </div>

            <p className="text-center text-text-secondary text-sm mt-6">
              {isArabic
                ? "هذه البطاقة خاصة بك فقط ولا يمكن لغيرك رؤيتها"
                : "This card is visible only to you"}
            </p>
          </div>
        )}

        {activeTab === "security" && (
          <div className="max-w-2xl mx-auto space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Lock className="w-5 h-5" />
                  {isArabic ? "تغيير كلمة المرور" : "Change Password"}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-text mb-1.5">
                      {isArabic ? "كلمة المرور الحالية" : "Current Password"}
                    </label>
                    <input
                      type="password"
                      value={currentPassword}
                      onChange={(e) => setCurrentPassword(e.target.value)}
                      className="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-text mb-1.5">
                      {isArabic ? "كلمة المرور الجديدة" : "New Password"}
                    </label>
                    <input
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      className="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-text mb-1.5">
                      {isArabic ? "تأكيد كلمة المرور الجديدة" : "Confirm New Password"}
                    </label>
                    <input
                      type="password"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      className="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
                    />
                  </div>
                  {passwordError && (
                    <p className="text-sm text-red-600">{passwordError}</p>
                  )}
                  {passwordSuccess && (
                    <p className="text-sm text-green-600">{passwordSuccess}</p>
                  )}
                  <Button
                    onClick={handleChangePassword}
                    disabled={changingPassword || !currentPassword || !newPassword}
                  >
                    {changingPassword ? (
                      <Loader2 className="w-4 h-4 animate-spin ml-2" />
                    ) : (
                      <Lock className="w-4 h-4 ml-2" />
                    )}
                    {isArabic ? "تغيير كلمة المرور" : "Change Password"}
                  </Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Shield className="w-5 h-5" />
                  {isArabic ? "التحقق بخطوتين" : "Two-Factor Authentication"}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">
                      {isArabic ? "حماية إضافية لحسابك" : "Extra security for your account"}
                    </p>
                    <p className="text-text-secondary text-sm">
                      {isArabic
                        ? "أضف طبقة حماية إضافية عند تسجيل الدخول"
                        : "Add an extra layer of protection when logging in"}
                    </p>
                  </div>
                  <button className="relative inline-flex h-6 w-11 items-center rounded-full bg-border transition-colors">
                    <span className="inline-block h-4 w-4 transform rounded-full bg-white transition-transform" />
                  </button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Bell className="w-5 h-5" />
                  {isArabic ? "إشعارات الأمان" : "Security Notifications"}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">
                      {isArabic ? "تنبيهات تسجيل الدخول" : "Login Alerts"}
                    </p>
                    <p className="text-text-secondary text-sm">
                      {isArabic
                        ? "استلام إشعار عند تسجيل الدخول من جهاز جديد"
                        : "Get notified when logging in from a new device"}
                    </p>
                  </div>
                  <button className="relative inline-flex h-6 w-11 items-center rounded-full bg-primary transition-colors">
                    <span className="inline-block h-4 w-4 transform translate-x-1 rounded-full bg-white transition-transform" />
                  </button>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Password Reset Modal */}
        {showPasswordModal && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
            <div className="bg-surface rounded-2xl p-8 max-w-md w-full mx-4 shadow-2xl">
              {!passwordSent ? (
                <>
                  <h3 className="text-xl font-bold mb-4">
                    {isArabic ? "تغيير كلمة المرور" : "Change Password"}
                  </h3>
                  <p className="text-text-secondary mb-6">
                    {isArabic
                      ? "أدخل بريدك الإلكتروني لإرسال رابط تغيير كلمة المرور"
                      : "Enter your email to receive a password reset link"}
                  </p>
                  <Input
                    type="email"
                    value={resetEmail}
                    onChange={(e) => setResetEmail(e.target.value)}
                    placeholder={isArabic ? "البريد الإلكتروني" : "Email"}
                    className="mb-4"
                  />
                  <div className="flex gap-3">
                    <Button
                      variant="outline"
                      className="flex-1"
                      onClick={() => {
                        setShowPasswordModal(false);
                        setPasswordSent(false);
                      }}
                    >
                      {isArabic ? "إلغاء" : "Cancel"}
                    </Button>
                    <Button
                      className="flex-1"
                      onClick={handleSendResetEmail}
                      disabled={sendingReset || !resetEmail}
                    >
                      {sendingReset ? (
                        <Loader2 className="w-4 h-4 animate-spin ml-2" />
                      ) : (
                        <Mail className="w-4 h-4 ml-2" />
                      )}
                      {isArabic ? "إرسال" : "Send"}
                    </Button>
                  </div>
                </>
              ) : (
                <div className="text-center">
                  <div className="w-16 h-16 bg-success-light rounded-full flex items-center justify-center mx-auto mb-4">
                    <Check className="w-8 h-8 text-success" />
                  </div>
                  <h3 className="text-xl font-bold mb-2">
                    {isArabic ? "تم الإرسال بنجاح!" : "Email Sent!"}
                  </h3>
                  <p className="text-text-secondary mb-6">
                    {isArabic
                      ? `تم إرسال رابط تغيير كلمة المرور إلى ${resetEmail}`
                      : `Password reset link sent to ${resetEmail}`}
                  </p>
                  <Button
                    className="w-full"
                    onClick={() => {
                      setShowPasswordModal(false);
                      setPasswordSent(false);
                    }}
                  >
                    {isArabic ? "حسناً" : "OK"}
                  </Button>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
