"use client"

import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { sanitizeInput } from "@/lib/security/sanitize"
import { User, Mail, Lock, Eye, EyeOff, Save, Shield, Clock, Calendar, Globe, Languages } from "lucide-react"
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 { useToastEnhanced } from "@/hooks/use-toast-enhanced"
import {
  profileUpdateSchema,
  emailChangeSchema,
  passwordChangeSchema,
  type ProfileUpdateInput,
  type EmailChangeInput,
  type PasswordChangeInput,
} from "@/lib/validations/profile"
import { adminProfileStore, type AdminProfile } from "@/lib/data/admin-profile"

const timezones = [
  { value: "Asia/Kolkata", label: "India (IST)" },
  { value: "America/New_York", label: "New York (EST)" },
  { value: "America/Los_Angeles", label: "Los Angeles (PST)" },
  { value: "Europe/London", label: "London (GMT)" },
  { value: "Europe/Paris", label: "Paris (CET)" },
  { value: "Asia/Dubai", label: "Dubai (GST)" },
  { value: "Asia/Singapore", label: "Singapore (SGT)" },
  { value: "Australia/Sydney", label: "Sydney (AEST)" },
]

const languages = [
  { value: "en", label: "English" },
  { value: "hi", label: "Hindi" },
  { value: "ta", label: "Tamil" },
  { value: "te", label: "Telugu" },
  { value: "mr", label: "Marathi" },
  { value: "bn", label: "Bengali" },
]

export function AdminProfileClient() {
  const [profile, setProfile] = useState<AdminProfile | null>(null)
  const [activeTab, setActiveTab] = useState("profile")
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({})
  const toast = useToastEnhanced()

  useEffect(() => {
    setProfile(adminProfileStore.getProfile())
  }, [])

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

  // 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 = (data: ProfileUpdateInput) => {
    const sanitized = {
      firstName: sanitizeInput(data.firstName),
      lastName: sanitizeInput(data.lastName),
      phone: sanitizeInput(data.phone),
      timezone: data.timezone,
      language: data.language,
    }
    adminProfileStore.updateProfile(sanitized)
    setProfile(adminProfileStore.getProfile())
    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
    }
    adminProfileStore.updateEmail(sanitizeInput(data.newEmail))
    setProfile(adminProfileStore.getProfile())
    emailForm.reset()
    toast.success({ title: "Email updated", description: "Your email address has been changed." })
  }

  const onPasswordSubmit = (data: PasswordChangeInput) => {
    const result = adminProfileStore.changePassword(data.currentPassword, data.newPassword)
    if (!result.success) {
      toast.error({ title: "Error", description: result.message })
      return
    }
    passwordForm.reset()
    toast.success({ title: "Password changed", description: "Your password has been updated successfully." })
  }

  const toggleTwoFactor = () => {
    if (!profile) return
    adminProfileStore.updateProfile({ twoFactorEnabled: !profile.twoFactorEnabled })
    setProfile(adminProfileStore.getProfile())
    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 (!profile) {
    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>
    )
  }

  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="h-20 w-20 rounded-2xl bg-gradient-to-br from-primary to-primary/80 flex items-center justify-center shadow-lg shadow-primary/25">
              <span className="text-3xl font-bold text-primary-foreground">
                {profile.firstName.charAt(0)}
                {profile.lastName.charAt(0)}
              </span>
            </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: {profile.lastLogin.toLocaleDateString()}
                </Badge>
                <Badge variant="outline" className="rounded-lg gap-1.5">
                  <Calendar className="h-3 w-3" aria-hidden="true" />
                  Member since: {profile.createdAt.toLocaleDateString()}
                </Badge>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <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={profileForm.watch("timezone")}
                      onValueChange={(v) => profileForm.setValue("timezone", v)}
                    >
                      <SelectTrigger id="timezone" className="rounded-xl">
                        <SelectValue placeholder="Select timezone" />
                      </SelectTrigger>
                      <SelectContent>
                        {timezones.map((tz) => (
                          <SelectItem key={tz.value} value={tz.value}>
                            {tz.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={profileForm.watch("language")}
                      onValueChange={(v) => profileForm.setValue("language", v)}
                    >
                      <SelectTrigger id="language" className="rounded-xl">
                        <SelectValue placeholder="Select language" />
                      </SelectTrigger>
                      <SelectContent>
                        {languages.map((lang) => (
                          <SelectItem key={lang.value} value={lang.value}>
                            {lang.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'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>
  )
}
