'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { signOut } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { AvatarUpload } from '@/components/shared/avatar-upload'
import { UserAvatar } from '@/components/shared/user-avatar'
import { TagInput } from '@/components/shared/tag-input'
import {
  Loader2,
  Save,
  Camera,
  Lock,
  Bell,
  Mail,
  Calendar,
  Trash2,
  User,
  Tags,
} from 'lucide-react'

export default function ProfileSettingsPage() {
  const router = useRouter()
  const { data: user, isLoading, refetch } = trpc.user.me.useQuery()
  const { data: avatarUrl } = trpc.avatar.getUrl.useQuery()
  const utils = trpc.useUtils()
  const updateProfile = trpc.user.updateProfile.useMutation({
    onSuccess: () => utils.user.me.invalidate(),
  })
  const changePassword = trpc.user.changePassword.useMutation()
  const deleteAccount = trpc.user.deleteAccount.useMutation()

  // Profile form state
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [bio, setBio] = useState('')
  const [phoneNumber, setPhoneNumber] = useState('')
  const [notificationPreference, setNotificationPreference] = useState('EMAIL')
  const [expertiseTags, setExpertiseTags] = useState<string[]>([])
  const [digestFrequency, setDigestFrequency] = useState('none')
  const [preferredWorkload, setPreferredWorkload] = useState<number | null>(null)
  const [availabilityStart, setAvailabilityStart] = useState('')
  const [availabilityEnd, setAvailabilityEnd] = useState('')
  const [profileLoaded, setProfileLoaded] = useState(false)

  // Password form state
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmNewPassword, setConfirmNewPassword] = useState('')

  // Delete account state
  const [deletePassword, setDeletePassword] = useState('')
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)

  // Populate form when user data loads
  useEffect(() => {
    if (user && !profileLoaded) {
      setName(user.name || '')
      setEmail(user.email || '')
      const meta = (user.metadataJson as Record<string, unknown>) || {}
      setBio((meta.bio as string) || '')
      setPhoneNumber(user.phoneNumber || '')
      setNotificationPreference(user.notificationPreference || 'EMAIL')
      setExpertiseTags(user.expertiseTags || [])
      setDigestFrequency(user.digestFrequency || 'none')
      setPreferredWorkload(user.preferredWorkload ?? null)
      const avail = user.availabilityJson as Array<{ start?: string; end?: string }> | null
      if (avail && avail.length > 0) {
        setAvailabilityStart(avail[0].start || '')
        setAvailabilityEnd(avail[0].end || '')
      }
      setProfileLoaded(true)
    }
  }, [user, profileLoaded])

  const handleSaveProfile = async () => {
    try {
      await updateProfile.mutateAsync({
        name: name || undefined,
        bio,
        phoneNumber: phoneNumber || null,
        notificationPreference: notificationPreference as 'EMAIL' | 'WHATSAPP' | 'BOTH' | 'NONE',
        expertiseTags,
        digestFrequency: digestFrequency as 'none' | 'daily' | 'weekly',
        preferredWorkload: preferredWorkload ?? undefined,
        availabilityJson: (availabilityStart || availabilityEnd) ? [{
          start: availabilityStart || '',
          end: availabilityEnd || '',
        }] : undefined,
      })
      toast.success('Profile updated successfully')
      refetch()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to update profile')
    }
  }

  const handleChangePassword = async () => {
    if (newPassword !== confirmNewPassword) {
      toast.error('New passwords do not match')
      return
    }

    try {
      await changePassword.mutateAsync({
        currentPassword,
        newPassword,
        confirmNewPassword,
      })
      toast.success('Password changed successfully')
      setCurrentPassword('')
      setNewPassword('')
      setConfirmNewPassword('')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to change password')
    }
  }

  const handleDeleteAccount = async () => {
    try {
      await deleteAccount.mutateAsync({ password: deletePassword })
      toast.success('Account deleted')
      setDeleteDialogOpen(false)
      signOut({ callbackUrl: '/login' })
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to delete account')
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-[200px] w-full" />
        <Skeleton className="h-[200px] w-full" />
      </div>
    )
  }

  if (!user) return null

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Profile Settings</h1>
        <p className="text-muted-foreground">
          Manage your personal information and preferences
        </p>
      </div>

      {/* Profile Photo */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Camera className="h-5 w-5" />
            Profile Photo
          </CardTitle>
          <CardDescription>
            Click the button below to upload a new profile picture
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4">
            <UserAvatar
              user={{ name: user.name, email: user.email }}
              avatarUrl={avatarUrl}
              size="xl"
            />
            <AvatarUpload
              user={{ name: user.name, email: user.email, profileImageKey: user.profileImageKey }}
              currentAvatarUrl={avatarUrl}
              onUploadComplete={() => refetch()}
            >
              <Button variant="outline" size="sm">
                <Camera className="mr-2 h-4 w-4" />
                Change Photo
              </Button>
            </AvatarUpload>
          </div>
        </CardContent>
      </Card>

      {/* Personal Information */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <User className="h-5 w-5" />
            Personal Information
          </CardTitle>
          <CardDescription>
            Update your name, bio, and contact information
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              value={email}
              readOnly
              disabled
              placeholder="you@example.com"
            />
            <p className="text-xs text-muted-foreground">
              Used for login and notifications. Contact an administrator to
              change your email address.
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="name">Name</Label>
            <Input
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Your full name"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="bio">Bio</Label>
            <Textarea
              id="bio"
              value={bio}
              onChange={(e) => setBio(e.target.value)}
              placeholder="Tell us a bit about yourself..."
              rows={3}
              maxLength={1000}
            />
            <p className="text-xs text-muted-foreground">
              {bio.length}/1000 characters
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="phone">Phone Number</Label>
            <Input
              id="phone"
              value={phoneNumber}
              onChange={(e) => setPhoneNumber(e.target.value)}
              placeholder="+33 6 12 34 56 78"
            />
          </div>

        </CardContent>
      </Card>

      {/* Notifications */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bell className="h-5 w-5" />
            Notifications
          </CardTitle>
          <CardDescription>
            Choose how you want to receive notifications
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="notification-pref">Notification Preference</Label>
            <Select
              value={notificationPreference}
              onValueChange={setNotificationPreference}
            >
              <SelectTrigger id="notification-pref">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="EMAIL">Email only</SelectItem>
                <SelectItem value="WHATSAPP">WhatsApp only</SelectItem>
                <SelectItem value="BOTH">Email & WhatsApp</SelectItem>
                <SelectItem value="NONE">None</SelectItem>
              </SelectContent>
            </Select>
          </div>

        </CardContent>
      </Card>

      {/* Email Digest */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Email Digest
          </CardTitle>
          <CardDescription>
            Receive periodic email summaries of pending actions and updates
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="digest-frequency">Digest Frequency</Label>
            <Select value={digestFrequency} onValueChange={setDigestFrequency}>
              <SelectTrigger id="digest-frequency">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">No digest</SelectItem>
                <SelectItem value="daily">Daily summary</SelectItem>
                <SelectItem value="weekly">Weekly summary</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground">
              Get a summary of pending evaluations, upcoming deadlines, and recent activity
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Availability & Workload */}
      {(user.role === 'JURY_MEMBER' || user.role === 'SUPER_ADMIN' || user.role === 'PROGRAM_ADMIN') && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5" />
              Availability & Workload
            </CardTitle>
            <CardDescription>
              Set your availability window and preferred evaluation workload
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="avail-start">Available From</Label>
                <Input
                  id="avail-start"
                  type="date"
                  value={availabilityStart}
                  onChange={(e) => setAvailabilityStart(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="avail-end">Available Until</Label>
                <Input
                  id="avail-end"
                  type="date"
                  value={availabilityEnd}
                  onChange={(e) => setAvailabilityEnd(e.target.value)}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="workload">Preferred Workload (projects per round)</Label>
              <Input
                id="workload"
                type="number"
                min={1}
                max={50}
                value={preferredWorkload ?? ''}
                onChange={(e) => setPreferredWorkload(e.target.value ? parseInt(e.target.value) : null)}
                placeholder="e.g. 10"
              />
              <p className="text-xs text-muted-foreground">
                How many projects you prefer to evaluate per round
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Expertise Tags */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Tags className="h-5 w-5" />
            Expertise Tags
          </CardTitle>
          <CardDescription>
            Select your areas of expertise to help with project matching
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <TagInput
            value={expertiseTags}
            onChange={setExpertiseTags}
            placeholder="Select your expertise areas..."
            maxTags={15}
          />

        </CardContent>
      </Card>

      {/* Save All Profile Changes */}
      <div className="flex justify-end">
        <Button
          onClick={handleSaveProfile}
          disabled={updateProfile.isPending}
          size="lg"
        >
          {updateProfile.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Save All Changes
        </Button>
      </div>

      {/* Change Password */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Lock className="h-5 w-5" />
            Change Password
          </CardTitle>
          <CardDescription>
            Update your account password
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="current-password">Current Password</Label>
            <Input
              id="current-password"
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              placeholder="Enter current password"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="new-password">New Password</Label>
            <Input
              id="new-password"
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="Enter new password"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirm-password">Confirm New Password</Label>
            <Input
              id="confirm-password"
              type="password"
              value={confirmNewPassword}
              onChange={(e) => setConfirmNewPassword(e.target.value)}
              placeholder="Confirm new password"
            />
          </div>

          <div className="flex justify-end">
            <Button
              onClick={handleChangePassword}
              disabled={changePassword.isPending || !currentPassword || !newPassword || !confirmNewPassword}
            >
              {changePassword.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Lock className="mr-2 h-4 w-4" />
              )}
              Change Password
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Danger Zone */}
      {user.role !== 'SUPER_ADMIN' && (
        <Card className="border-destructive/50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <Trash2 className="h-5 w-5" />
              Danger Zone
            </CardTitle>
            <CardDescription>
              Permanently delete your account and all associated data
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
              <DialogTrigger asChild>
                <Button variant="destructive">
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete Account
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Delete Account</DialogTitle>
                  <DialogDescription>
                    This action is permanent and cannot be undone. All your data,
                    evaluations, and assignments will be removed.
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label htmlFor="delete-password">
                      Enter your password to confirm
                    </Label>
                    <Input
                      id="delete-password"
                      type="password"
                      value={deletePassword}
                      onChange={(e) => setDeletePassword(e.target.value)}
                      placeholder="Your password"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => {
                      setDeleteDialogOpen(false)
                      setDeletePassword('')
                    }}
                  >
                    Cancel
                  </Button>
                  <Button
                    variant="destructive"
                    onClick={handleDeleteAccount}
                    disabled={deleteAccount.isPending || !deletePassword}
                  >
                    {deleteAccount.isPending ? (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    ) : (
                      <Trash2 className="mr-2 h-4 w-4" />
                    )}
                    Delete Account
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
