'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { useProfile, useUpdateProfile } from '@/hooks/use-profile'
import { ProfilePhotoUpload } from '@/components/profile/profile-photo-upload'
import { PasswordChangeDialog } from '@/components/profile/password-change-dialog'
import { TwoFactorSettings } from '@/components/settings/two-factor-settings'
import {
  User,
  Mail,
  Shield,
  Key,
  Loader2,
  Save,
  AlertCircle,
  CheckCircle,
  ShieldCheck,
} from 'lucide-react'

export default function ProfilePage() {
  const { data: profile, isLoading, error } = useProfile()
  const updateProfileMutation = useUpdateProfile()

  const [name, setName] = useState('')
  const [isNameDirty, setIsNameDirty] = useState(false)
  const [showPasswordDialog, setShowPasswordDialog] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState(false)
  const [saveError, setSaveError] = useState<string | null>(null)

  // Initialize name when profile loads
  if (profile && !isNameDirty && name !== (profile.name || '')) {
    setName(profile.name || '')
  }

  const handleNameChange = (value: string) => {
    setName(value)
    setIsNameDirty(true)
    setSaveSuccess(false)
    setSaveError(null)
  }

  const handleSaveName = async () => {
    setSaveError(null)
    setSaveSuccess(false)
    try {
      await updateProfileMutation.mutateAsync({ name: name.trim() })
      setIsNameDirty(false)
      setSaveSuccess(true)
      setTimeout(() => setSaveSuccess(false), 3000)
    } catch (err) {
      if (err && typeof err === 'object' && 'data' in err) {
        const apiError = err as { data?: { error?: string } }
        setSaveError(apiError.data?.error || 'Failed to save profile')
      } else {
        setSaveError(err instanceof Error ? err.message : 'Failed to save profile')
      }
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (error || !profile) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
        <AlertCircle className="h-12 w-12 text-destructive" />
        <p className="text-lg text-muted-foreground">Failed to load profile</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">My Profile</h1>
        <p className="text-muted-foreground">
          Manage your account settings and security preferences
        </p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Profile Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5 text-muted-foreground" />
              Profile Information
            </CardTitle>
            <CardDescription>
              Your basic profile details and photo
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Photo Upload */}
            <ProfilePhotoUpload
              currentPhotoUrl={profile.profilePhotoUrl}
              name={profile.name}
              email={profile.email}
            />

            <Separator />

            {/* Name Field */}
            <div className="space-y-2">
              <Label htmlFor="name" className="flex items-center gap-2">
                Display Name
                {isNameDirty && (
                  <Badge variant="secondary" className="text-xs">Modified</Badge>
                )}
              </Label>
              <div className="flex gap-2">
                <Input
                  id="name"
                  placeholder="Enter your name"
                  value={name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  disabled={updateProfileMutation.isPending}
                />
                <Button
                  onClick={handleSaveName}
                  disabled={!isNameDirty || updateProfileMutation.isPending}
                  className="gap-2"
                >
                  {updateProfileMutation.isPending ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Save className="h-4 w-4" />
                  )}
                  Save
                </Button>
              </div>
              {saveSuccess && (
                <p className="text-sm text-green-600 flex items-center gap-1">
                  <CheckCircle className="h-4 w-4" />
                  Name saved successfully
                </p>
              )}
              {saveError && (
                <p className="text-sm text-destructive flex items-center gap-1">
                  <AlertCircle className="h-4 w-4" />
                  {saveError}
                </p>
              )}
            </div>

            <Separator />

            {/* Email (Read-only) */}
            <div className="space-y-2">
              <Label className="flex items-center gap-2">
                <Mail className="h-4 w-4 text-muted-foreground" />
                Email Address
              </Label>
              <Input
                value={profile.email}
                disabled
                className="bg-muted"
              />
              <p className="text-xs text-muted-foreground">
                Email cannot be changed
              </p>
            </div>

            {/* Role (Read-only) */}
            <div className="space-y-2">
              <Label className="flex items-center gap-2">
                <Shield className="h-4 w-4 text-muted-foreground" />
                Role
              </Label>
              <div>
                <Badge variant="outline" className="text-sm">
                  {profile.role}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Security */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ShieldCheck className="h-5 w-5 text-muted-foreground" />
              Security
            </CardTitle>
            <CardDescription>
              Manage your password and two-factor authentication
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Password */}
            <div className="space-y-3">
              <Label className="flex items-center gap-2">
                <Key className="h-4 w-4 text-muted-foreground" />
                Password
              </Label>
              <p className="text-sm text-muted-foreground">
                Keep your account secure with a strong password
              </p>
              <Button
                variant="outline"
                onClick={() => setShowPasswordDialog(true)}
                className="w-full sm:w-auto"
              >
                Change Password
              </Button>
            </div>

            <Separator />

            {/* Two-Factor Authentication */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="flex items-center gap-2">
                  <Shield className="h-4 w-4 text-muted-foreground" />
                  Two-Factor Authentication
                </Label>
                {profile.twoFactorEnabled ? (
                  <Badge variant="default" className="bg-green-600 hover:bg-green-600">
                    Enabled
                  </Badge>
                ) : (
                  <Badge variant="secondary">
                    Disabled
                  </Badge>
                )}
              </div>
              <p className="text-sm text-muted-foreground">
                Add an extra layer of security to your account using an authenticator app
              </p>
              <TwoFactorSettings />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Password Change Dialog */}
      <PasswordChangeDialog
        open={showPasswordDialog}
        onOpenChange={setShowPasswordDialog}
      />
    </div>
  )
}
