'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { toast } from 'sonner'
import { TagInput } from '@/components/shared/tag-input'
import {
  ArrowLeft,
  Save,
  Mail,
  User,
  Shield,
  Loader2,
  CheckCircle,
  AlertCircle,
} from 'lucide-react'

export default function UserEditPage() {
  const params = useParams()
  const router = useRouter()
  const userId = params.id as string

  const { data: user, isLoading, refetch } = trpc.user.get.useQuery({ id: userId })
  const updateUser = trpc.user.update.useMutation()
  const sendInvitation = trpc.user.sendInvitation.useMutation()

  const [name, setName] = useState('')
  const [role, setRole] = useState<'JURY_MEMBER' | 'OBSERVER' | 'PROGRAM_ADMIN'>('JURY_MEMBER')
  const [status, setStatus] = useState<'INVITED' | 'ACTIVE' | 'SUSPENDED'>('INVITED')
  const [expertiseTags, setExpertiseTags] = useState<string[]>([])
  const [maxAssignments, setMaxAssignments] = useState<string>('')

  // Populate form when user data loads
  useEffect(() => {
    if (user) {
      setName(user.name || '')
      setRole(user.role as 'JURY_MEMBER' | 'OBSERVER' | 'PROGRAM_ADMIN')
      setStatus(user.status as 'INVITED' | 'ACTIVE' | 'SUSPENDED')
      setExpertiseTags(user.expertiseTags || [])
      setMaxAssignments(user.maxAssignments?.toString() || '')
    }
  }, [user])

  const handleSave = async () => {
    try {
      await updateUser.mutateAsync({
        id: userId,
        name: name || null,
        role,
        status,
        expertiseTags,
        maxAssignments: maxAssignments ? parseInt(maxAssignments) : null,
      })
      toast.success('User updated successfully')
      router.push('/admin/users')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to update user')
    }
  }

  const handleSendInvitation = async () => {
    try {
      await sendInvitation.mutateAsync({ userId })
      toast.success('Invitation email sent successfully')
      refetch()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to send invitation')
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-9 w-32" />
        </div>
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-48" />
            <Skeleton className="h-4 w-72" />
          </CardHeader>
          <CardContent className="space-y-4">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
          </CardContent>
        </Card>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="space-y-6">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>User not found</AlertTitle>
          <AlertDescription>
            The user you&apos;re looking for does not exist.
          </AlertDescription>
        </Alert>
        <Button asChild>
          <Link href="/admin/users">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Users
          </Link>
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/admin/users">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Users
          </Link>
        </Button>
      </div>

      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Edit User</h1>
          <p className="text-muted-foreground">{user.email}</p>
        </div>
        {user.status === 'INVITED' && (
          <Button
            variant="outline"
            onClick={handleSendInvitation}
            disabled={sendInvitation.isPending}
          >
            {sendInvitation.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Mail className="mr-2 h-4 w-4" />
            )}
            Send Invitation
          </Button>
        )}
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Basic Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5" />
              Basic Information
            </CardTitle>
            <CardDescription>
              Update the user&apos;s profile information
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" value={user.email} disabled />
              <p className="text-xs text-muted-foreground">
                Email cannot be changed
              </p>
            </div>

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

            <div className="space-y-2">
              <Label htmlFor="role">Role</Label>
              <Select value={role} onValueChange={(v) => setRole(v as typeof role)}>
                <SelectTrigger id="role">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="JURY_MEMBER">Jury Member</SelectItem>
                  <SelectItem value="OBSERVER">Observer</SelectItem>
                  <SelectItem value="PROGRAM_ADMIN">Program Admin</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select value={status} onValueChange={(v) => setStatus(v as typeof status)}>
                <SelectTrigger id="status">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="INVITED">Invited</SelectItem>
                  <SelectItem value="ACTIVE">Active</SelectItem>
                  <SelectItem value="SUSPENDED">Suspended</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Assignment Settings */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Shield className="h-5 w-5" />
              Assignment Settings
            </CardTitle>
            <CardDescription>
              Configure expertise tags and assignment limits
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label>Expertise Tags</Label>
              <TagInput
                value={expertiseTags}
                onChange={setExpertiseTags}
                placeholder="Select expertise tags..."
                maxTags={15}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="maxAssignments">Max Assignments</Label>
              <Input
                id="maxAssignments"
                type="number"
                min="1"
                max="100"
                value={maxAssignments}
                onChange={(e) => setMaxAssignments(e.target.value)}
                placeholder="Unlimited"
              />
              <p className="text-xs text-muted-foreground">
                Maximum number of projects this user can be assigned
              </p>
            </div>

            {user._count && (
              <div className="pt-4 border-t">
                <h4 className="font-medium mb-2">Statistics</h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">Total Assignments</p>
                    <p className="text-2xl font-semibold">{user._count.assignments}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">Last Login</p>
                    <p className="text-lg">
                      {user.lastLoginAt
                        ? new Date(user.lastLoginAt).toLocaleDateString()
                        : 'Never'}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Status Alert */}
      {user.status === 'INVITED' && (
        <Alert>
          <Mail className="h-4 w-4" />
          <AlertTitle>Invitation Pending</AlertTitle>
          <AlertDescription>
            This user hasn&apos;t accepted their invitation yet. You can resend the
            invitation email using the button above.
          </AlertDescription>
        </Alert>
      )}

      {/* Save Button */}
      <div className="flex justify-end gap-4">
        <Button variant="outline" asChild>
          <Link href="/admin/users">Cancel</Link>
        </Button>
        <Button onClick={handleSave} disabled={updateUser.isPending}>
          {updateUser.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Save Changes
        </Button>
      </div>
    </div>
  )
}
