"use client";

import { useState, useEffect, useRef } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { sanitizeInput } from "@/core/security/sanitize";
import {
  User,
  Mail,
  Lock,
  Eye,
  EyeOff,
  Save,
  Shield,
  Clock,
  Calendar,
  Globe,
  Languages,
  Camera,
  Loader2,
} from "lucide-react";
import Image from "next/image";
import { getStorageUrl } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Cropper, type CropperRef } from "react-advanced-cropper";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import {
  changePasswordAction,
  changeProfileImageAction,
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import type { User as AuthUser } from "@/core/api";
import {
  profileUpdateSchema,
  emailChangeSchema,
  passwordChangeSchema,
  type ProfileUpdateInput,
  type EmailChangeInput,
  type PasswordChangeInput,
} from "@/lib/validations/profile";
import {
  adminProfileStore,
  type AdminProfile,
} from "@/roles/admin/services/admin-profile.service";

const READ_ONLY_TIMEZONE = { value: "Asia/Kolkata", label: "India IST" };
const READ_ONLY_LANGUAGE = { value: "en", label: "English" };

function toValidDate(value?: string | null, fallback?: Date) {
  if (!value) return fallback ?? new Date();
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return fallback ?? new Date();
  }
  return parsed;
}

function formatDateSafe(value: Date) {
  if (Number.isNaN(value.getTime())) return "-";
  return value.toLocaleDateString();
}

const ADMIN_PROFILE_IMAGE_UPDATED_EVENT = "admin-profile-image-updated";

function getProfileImageSrc(
  value: string | null | undefined,
  cacheKey?: number
) {
  if (!value?.trim()) return null;
  if (value.startsWith("data:") || value.startsWith("blob:")) return value;
  const imageUrl = getStorageUrl(value);
  if (!cacheKey) return imageUrl;
  const separator = imageUrl.includes("?") ? "&" : "?";
  return `${imageUrl}${separator}v=${cacheKey}`;
}

export function AdminProfileClient() {
  const [isLoading, setIsLoading] = useState(true);
  const [profile, setProfile] = useState<AdminProfile | null>(null);
  const [activeTab, setActiveTab] = useState("profile");
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>(
    {}
  );
  const [profileImageSrc, setProfileImageSrc] = useState<string | null>(null);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [cropperOpen, setCropperOpen] = useState(false);
  const [cropSource, setCropSource] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const cropperRef = useRef<CropperRef>(null);
  const toast = useToastEnhanced();

  useEffect(() => {
    const loadProfile = async () => {
      setIsLoading(true);
      try {
        const result = await getProfileAction();
        if (!result.success || !result.data) {
          setProfile(null);
          toast.error({
            title: "Error",
            description: result.error || "Failed to load profile details.",
          });
          return;
        }

        const user = result.data as AuthUser;
        const firstName =
          user.first_name?.trim() ||
          user.name?.split(" ").slice(0, 1).join(" ") ||
          "Admin";
        const lastName =
          user.last_name?.trim() ||
          user.name?.split(" ").slice(1).join(" ") ||
          "User";

        const createdAtDate = toValidDate(user.created_at, new Date());
        const updatedAtDate = toValidDate(user.updated_at, createdAtDate);

        setProfile({
          id: String(user.id),
          firstName,
          lastName,
          email: user.email || "",
          phone: user.phone_number || "",
          avatar: "",
          timezone: READ_ONLY_TIMEZONE.value,
          language: READ_ONLY_LANGUAGE.value,
          twoFactorEnabled: false,
          lastLogin: updatedAtDate,
          createdAt: createdAtDate,
        });
        setProfileImageSrc(getProfileImageSrc(user.profile_image));
      } catch {
        setProfile(null);
        toast.error({
          title: "Error",
          description: "Failed to load profile details.",
        });
      } finally {
        setIsLoading(false);
      }
    };

    loadProfile();
  }, [toast]);

  const togglePassword = (key: string) => {
    setShowPasswords((prev) => ({ ...prev, [key]: !prev[key] }));
  };

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

    const allowedTypes = new Set(["image/jpeg", "image/jpg", "image/png"]);
    const extension = file.name.split(".").pop()?.toLowerCase();
    const allowedExtensions = new Set(["jpg", "jpeg", "png"]);
    if (
      !allowedTypes.has(file.type.toLowerCase()) &&
      !(extension && allowedExtensions.has(extension))
    ) {
      toast.error({
        title: "Invalid file",
        description: "Please upload a JPG, JPEG, or PNG image.",
      });
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error({
        title: "File too large",
        description: "Please upload an image under 5MB.",
      });
      return;
    }

    if (cropSource) URL.revokeObjectURL(cropSource);
    setCropSource(URL.createObjectURL(file));
    setCropperOpen(true);
  };

  const handleCropperOpenChange = (open: boolean) => {
    setCropperOpen(open);
    if (!open && !isUploadingImage && cropSource) {
      URL.revokeObjectURL(cropSource);
      setCropSource(null);
    }
  };

  const refreshProfileImage = async () => {
    const updated = await getProfileAction();
    if (updated.success && updated.data) {
      const src = getProfileImageSrc(
        (updated.data as AuthUser).profile_image,
        Date.now()
      );
      if (src) {
        setProfileImageSrc(src);
        return src;
      }
    }
    return null;
  };

  const handleCropAndUpload = async () => {
    const canvas = cropperRef.current?.getCanvas();
    if (!canvas) {
      toast.error({
        title: "Crop failed",
        description: "Unable to crop image. Please try another image.",
      });
      return;
    }

    const previousImage = profileImageSrc;
    setIsUploadingImage(true);

    try {
      const blob = await new Promise<Blob | null>((resolve) =>
        canvas.toBlob(resolve, "image/png")
      );
      if (!blob) throw new Error("Unable to generate cropped image.");

      const croppedFile = new File([blob], `profile-${Date.now()}.png`, {
        type: "image/png",
      });
      const previewUrl = URL.createObjectURL(blob);
      setProfileImageSrc(previewUrl);

      const formData = new FormData();
      formData.append("profile_image", croppedFile);
      const result = await changeProfileImageAction(formData);

      if (!result.success)
        throw new Error(result.error || "Failed to update profile photo.");

      const uploadedUrl =
        typeof result.data === "string" && result.data.trim()
          ? getProfileImageSrc(result.data, Date.now())
          : null;

      if (uploadedUrl) {
        setProfileImageSrc(uploadedUrl);
        window.dispatchEvent(
          new CustomEvent(ADMIN_PROFILE_IMAGE_UPDATED_EVENT, {
            detail: { profileImage: uploadedUrl },
          })
        );
      } else {
        const refreshed = await refreshProfileImage();
        if (refreshed) {
          window.dispatchEvent(
            new CustomEvent(ADMIN_PROFILE_IMAGE_UPDATED_EVENT, {
              detail: { profileImage: refreshed },
            })
          );
        }
      }

      URL.revokeObjectURL(previewUrl);
      setCropperOpen(false);
      if (cropSource) {
        URL.revokeObjectURL(cropSource);
        setCropSource(null);
      }
      toast.success({
        title: "Photo updated",
        description: "Your profile photo has been updated successfully.",
      });
    } catch (error) {
      setProfileImageSrc(previousImage);
      toast.error({
        title: "Upload failed",
        description:
          error instanceof Error
            ? error.message
            : "Failed to update profile photo.",
      });
    } finally {
      setIsUploadingImage(false);
    }
  };

  // Profile Form
  const profileForm = useForm<ProfileUpdateInput>({
    resolver: zodResolver(profileUpdateSchema),
    values: profile
      ? {
          firstName: profile.firstName,
          lastName: profile.lastName,
          phone: profile.phone,
          timezone: profile.timezone,
          language: profile.language,
        }
      : undefined,
  });

  // Email Form
  const emailForm = useForm<EmailChangeInput>({
    resolver: zodResolver(emailChangeSchema),
    defaultValues: { newEmail: "", password: "" },
  });

  // Password Form
  const passwordForm = useForm<PasswordChangeInput>({
    resolver: zodResolver(passwordChangeSchema),
    defaultValues: {
      currentPassword: "",
      newPassword: "",
      confirmPassword: "",
    },
  });

  const onProfileSubmit = async (data: ProfileUpdateInput) => {
    console.log("[AdminProfile] Submitting profile update", data);

    const sanitized = {
      firstName: sanitizeInput(data.firstName),
      lastName: sanitizeInput(data.lastName),
      phone: sanitizeInput(data.phone),
      timezone: READ_ONLY_TIMEZONE.value,
      language: READ_ONLY_LANGUAGE.value,
    };

    console.log("[AdminProfile] Sanitized data for update", sanitized);

    const result = await updateProfileAction({
      first_name: sanitized.firstName,
      last_name: sanitized.lastName,
      phone_number: sanitized.phone,
    });

    if (!result.success) {
      toast.error({
        title: "Error",
        description: result.error || "Failed to update profile.",
      });
      return;
    }

    setProfile((prev) =>
      prev
        ? {
            ...prev,
            ...sanitized,
            timezone: READ_ONLY_TIMEZONE.value,
            language: READ_ONLY_LANGUAGE.value,
          }
        : prev
    );
    profileForm.reset(sanitized);

    console.log("[AdminProfile] Profile updated");
    toast.success({
      title: "Profile updated",
      description: "Your profile information has been saved.",
    });
  };

  const onEmailSubmit = (data: EmailChangeInput) => {
    const isValid = adminProfileStore.verifyPassword(data.password);
    if (!isValid) {
      toast.error({
        title: "Invalid password",
        description: "Please enter your correct current password.",
      });
      return;
    }
    const newEmail = sanitizeInput(data.newEmail);
    setProfile((prev) => (prev ? { ...prev, email: newEmail } : prev));
    emailForm.reset();
    toast.success({
      title: "Email updated",
      description: "Your email address has been changed.",
    });
  };

  const onPasswordSubmit = async (data: PasswordChangeInput) => {
    const result = await changePasswordAction({
      password: data.currentPassword,
      new_password: data.newPassword,
      new_password_confirmation: data.confirmPassword,
    });

    if (!result.success) {
      toast.error({
        title: "Error",
        description: result.error || "Failed to update password.",
      });
      return;
    }

    passwordForm.reset();
    toast.success({
      title: "Password changed",
      description: "Your password has been updated successfully.",
    });
  };

  const toggleTwoFactor = () => {
    if (!profile) return;
    setProfile((prev) =>
      prev ? { ...prev, twoFactorEnabled: !prev.twoFactorEnabled } : prev
    );
    toast.info({
      title: profile.twoFactorEnabled ? "2FA Disabled" : "2FA Enabled",
      description: profile.twoFactorEnabled
        ? "Two-factor authentication has been disabled."
        : "Two-factor authentication has been enabled.",
    });
  };

  if (isLoading) {
    return (
      <div className="admin-section">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="animate-pulse text-muted-foreground">
            Loading profile...
          </div>
        </div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="admin-section">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-muted-foreground">Unable to load profile.</div>
        </div>
      </div>
    );
  }

  return (
    <section aria-labelledby="profile-title" className="admin-section">
      <header className="admin-page-header">
        <h1 id="profile-title" className="admin-page-title">
          Manage Profile
        </h1>
        <p className="admin-page-description">
          Update your personal information, change your email or password, and
          manage security settings.
        </p>
      </header>

      {/* Profile Overview Card */}
      <Card className="admin-card rounded-xl border-0 mb-6">
        <CardContent className="p-6">
          <div className="flex flex-col sm:flex-row items-start sm:items-center gap-6">
            <div className="flex flex-col items-center gap-2">
              <div className="relative h-24 w-24 rounded-2xl overflow-hidden bg-gradient-to-br from-primary to-primary/80 flex items-center justify-center shadow-lg shadow-primary/25">
                {profileImageSrc ? (
                  <Image
                    src={profileImageSrc}
                    alt="Profile photo"
                    width={80}
                    height={80}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <span className="text-3xl font-bold text-primary-foreground">
                    {profile.firstName.charAt(0)}
                    {profile.lastName.charAt(0)}
                  </span>
                )}
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="rounded-xl gap-1.5 text-xs h-7 px-2"
                disabled={isUploadingImage}
                onClick={() => fileInputRef.current?.click()}
              >
                {isUploadingImage ? "Uploading…" : "Upload Photo"}
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/jpg,image/png"
                className="hidden"
                onChange={handleImageUpload}
              />
            </div>
            <div className="flex-1 space-y-1">
              <h2 className="text-2xl font-bold">
                {profile.firstName} {profile.lastName}
              </h2>
              <p className="text-muted-foreground">{profile.email}</p>
              <div className="flex flex-wrap items-center gap-2 pt-2">
                <Badge variant="secondary" className="rounded-lg gap-1.5">
                  <Shield className="h-3 w-3" aria-hidden="true" />
                  Administrator
                </Badge>
                <Badge variant="outline" className="rounded-lg gap-1.5">
                  <Clock className="h-3 w-3" aria-hidden="true" />
                  Last login: {formatDateSafe(profile.lastLogin)}
                </Badge>
                <Badge variant="outline" className="rounded-lg gap-1.5">
                  <Calendar className="h-3 w-3" aria-hidden="true" />
                  Member since: {formatDateSafe(profile.createdAt)}
                </Badge>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Crop & Upload Dialog */}
      <Dialog open={cropperOpen} onOpenChange={handleCropperOpenChange}>
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>Crop Profile Photo</DialogTitle>
            <DialogDescription>
              Adjust your image before updating your profile photo.
            </DialogDescription>
          </DialogHeader>
          {cropSource && (
            <div className="h-[420px] w-full overflow-hidden rounded-md border">
              <Cropper
                ref={cropperRef}
                src={cropSource}
                className="h-full w-full"
                stencilProps={{ aspectRatio: 1 }}
              />
            </div>
          )}
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => handleCropperOpenChange(false)}
              disabled={isUploadingImage}
            >
              Cancel
            </Button>
            <Button
              type="button"
              onClick={handleCropAndUpload}
              disabled={isUploadingImage}
            >
              {isUploadingImage && (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              )}
              {isUploadingImage ? "Uploading…" : "Crop & Upload"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Tabs
        value={activeTab}
        onValueChange={setActiveTab}
        className="space-y-6"
      >
        <TabsList className="inline-flex h-auto p-1 bg-muted/50 rounded-xl flex-wrap gap-1">
          <TabsTrigger
            value="profile"
            className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2"
          >
            <User className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Profile</span>
          </TabsTrigger>
          <TabsTrigger
            value="email"
            className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2"
          >
            <Mail className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Email</span>
          </TabsTrigger>
          <TabsTrigger
            value="password"
            className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2"
          >
            <Lock className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Password</span>
          </TabsTrigger>
          <TabsTrigger
            value="security"
            className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2"
          >
            <Shield className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Security</span>
          </TabsTrigger>
        </TabsList>

        {/* Profile Tab */}
        <TabsContent value="profile" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center shadow-lg">
                  <User className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Personal Information</CardTitle>
                  <CardDescription>
                    Update your name, phone number, and preferences.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form
                onSubmit={profileForm.handleSubmit(onProfileSubmit)}
                className="space-y-6"
              >
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="firstName">First Name</Label>
                    <Input
                      id="firstName"
                      {...profileForm.register("firstName")}
                      className="rounded-xl"
                    />
                    {profileForm.formState.errors.firstName && (
                      <p className="text-sm text-destructive">
                        {profileForm.formState.errors.firstName.message}
                      </p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="lastName">Last Name</Label>
                    <Input
                      id="lastName"
                      {...profileForm.register("lastName")}
                      className="rounded-xl"
                    />
                    {profileForm.formState.errors.lastName && (
                      <p className="text-sm text-destructive">
                        {profileForm.formState.errors.lastName.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone">Phone Number</Label>
                  <Input
                    id="phone"
                    {...profileForm.register("phone")}
                    className="rounded-xl"
                  />
                  {profileForm.formState.errors.phone && (
                    <p className="text-sm text-destructive">
                      {profileForm.formState.errors.phone.message}
                    </p>
                  )}
                </div>

                <Separator />

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label
                      htmlFor="timezone"
                      className="flex items-center gap-2"
                    >
                      <Globe className="h-4 w-4" aria-hidden="true" />
                      Timezone
                    </Label>
                    <Select value={READ_ONLY_TIMEZONE.value} disabled>
                      <SelectTrigger id="timezone" className="rounded-xl">
                        <SelectValue placeholder={READ_ONLY_TIMEZONE.label} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem
                          key={READ_ONLY_TIMEZONE.value}
                          value={READ_ONLY_TIMEZONE.value}
                        >
                          {READ_ONLY_TIMEZONE.label}
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label
                      htmlFor="language"
                      className="flex items-center gap-2"
                    >
                      <Languages className="h-4 w-4" aria-hidden="true" />
                      Language
                    </Label>
                    <Select value={READ_ONLY_LANGUAGE.value} disabled>
                      <SelectTrigger id="language" className="rounded-xl">
                        <SelectValue placeholder={READ_ONLY_LANGUAGE.label} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem
                          key={READ_ONLY_LANGUAGE.value}
                          value={READ_ONLY_LANGUAGE.value}
                        >
                          {READ_ONLY_LANGUAGE.label}
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex justify-end pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={profileForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Save Changes
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Email Tab */}
        <TabsContent value="email" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center shadow-lg">
                  <Mail className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Change Email Address</CardTitle>
                  <CardDescription>
                    Update your email address. You&apos;ll need to verify your
                    password.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="mb-6 p-4 rounded-xl bg-muted/50 border border-border/50">
                <p className="text-sm text-muted-foreground">Current email</p>
                <p className="font-medium">{profile.email}</p>
              </div>
              <form
                onSubmit={emailForm.handleSubmit(onEmailSubmit)}
                className="space-y-6"
              >
                <div className="space-y-2">
                  <Label htmlFor="newEmail">New Email Address</Label>
                  <Input
                    id="newEmail"
                    type="email"
                    placeholder="Enter new email address"
                    {...emailForm.register("newEmail")}
                    className="rounded-xl"
                  />
                  {emailForm.formState.errors.newEmail && (
                    <p className="text-sm text-destructive">
                      {emailForm.formState.errors.newEmail.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="emailPassword">Current Password</Label>
                  <div className="relative">
                    <Input
                      id="emailPassword"
                      type={showPasswords.emailPassword ? "text" : "password"}
                      placeholder="Enter your current password"
                      {...emailForm.register("password")}
                      className="rounded-xl pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                      onClick={() => togglePassword("emailPassword")}
                      aria-label={
                        showPasswords.emailPassword
                          ? "Hide password"
                          : "Show password"
                      }
                    >
                      {showPasswords.emailPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                  {emailForm.formState.errors.password && (
                    <p className="text-sm text-destructive">
                      {emailForm.formState.errors.password.message}
                    </p>
                  )}
                </div>

                <div className="flex justify-end pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={emailForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Update Email
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Password Tab */}
        <TabsContent value="password" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-500 flex items-center justify-center shadow-lg">
                  <Lock className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Change Password</CardTitle>
                  <CardDescription>
                    Update your password. Use a strong password with at least 8
                    characters.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form
                onSubmit={passwordForm.handleSubmit(onPasswordSubmit)}
                className="space-y-6"
              >
                <div className="space-y-2">
                  <Label htmlFor="currentPassword">Current Password</Label>
                  <div className="relative">
                    <Input
                      id="currentPassword"
                      type={showPasswords.currentPassword ? "text" : "password"}
                      placeholder="Enter current password"
                      {...passwordForm.register("currentPassword")}
                      className="rounded-xl pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                      onClick={() => togglePassword("currentPassword")}
                      aria-label={
                        showPasswords.currentPassword
                          ? "Hide password"
                          : "Show password"
                      }
                    >
                      {showPasswords.currentPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                  {passwordForm.formState.errors.currentPassword && (
                    <p className="text-sm text-destructive">
                      {passwordForm.formState.errors.currentPassword.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="newPassword">New Password</Label>
                  <div className="relative">
                    <Input
                      id="newPassword"
                      type={showPasswords.newPassword ? "text" : "password"}
                      placeholder="Enter new password"
                      {...passwordForm.register("newPassword")}
                      className="rounded-xl pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                      onClick={() => togglePassword("newPassword")}
                      aria-label={
                        showPasswords.newPassword
                          ? "Hide password"
                          : "Show password"
                      }
                    >
                      {showPasswords.newPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                  {passwordForm.formState.errors.newPassword && (
                    <p className="text-sm text-destructive">
                      {passwordForm.formState.errors.newPassword.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword">Confirm New Password</Label>
                  <div className="relative">
                    <Input
                      id="confirmPassword"
                      type={showPasswords.confirmPassword ? "text" : "password"}
                      placeholder="Confirm new password"
                      {...passwordForm.register("confirmPassword")}
                      className="rounded-xl pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                      onClick={() => togglePassword("confirmPassword")}
                      aria-label={
                        showPasswords.confirmPassword
                          ? "Hide password"
                          : "Show password"
                      }
                    >
                      {showPasswords.confirmPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                  {passwordForm.formState.errors.confirmPassword && (
                    <p className="text-sm text-destructive">
                      {passwordForm.formState.errors.confirmPassword.message}
                    </p>
                  )}
                </div>

                <div className="flex justify-end pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={passwordForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Update Password
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Security Tab */}
        <TabsContent value="security" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center shadow-lg">
                  <Shield className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Security Settings</CardTitle>
                  <CardDescription>
                    Manage two-factor authentication and security preferences.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="flex items-center justify-between p-4 rounded-xl bg-muted/50 border border-border/50">
                <div className="space-y-1">
                  <p className="font-medium">Two-Factor Authentication</p>
                  <p className="text-sm text-muted-foreground">
                    Add an extra layer of security to your account by requiring
                    a verification code.
                  </p>
                </div>
                <Switch
                  checked={profile.twoFactorEnabled}
                  onCheckedChange={toggleTwoFactor}
                  aria-label="Toggle two-factor authentication"
                />
              </div>

              <div className="p-4 rounded-xl bg-muted/50 border border-border/50">
                <p className="font-medium mb-2">Active Sessions</p>
                <p className="text-sm text-muted-foreground mb-4">
                  You are currently logged in on this device. Manage your active
                  sessions for security.
                </p>
                <Button variant="outline" className="rounded-xl bg-transparent">
                  View All Sessions
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </section>
  );
}
