'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 { Badge } from '@/components/ui/badge'
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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { toast } from 'sonner'
import { TagInput } from '@/components/shared/tag-input'
import { UserActivityLog } from '@/components/shared/user-activity-log'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  ArrowLeft,
  Save,
  Mail,
  User,
  Shield,
  Loader2,
  AlertCircle,
} from 'lucide-react'

export default function MemberDetailPage() {
  const params = useParams()
  const router = useRouter()
  const utils = trpc.useUtils()
  const userId = params.id as string

  const { data: user, isLoading, error, refetch } = trpc.user.get.useQuery({ id: userId })
  const { data: currentUser } = trpc.user.me.useQuery()
  const isSuperAdmin = currentUser?.role === 'SUPER_ADMIN'
  const updateUser = trpc.user.update.useMutation()
  const sendInvitation = trpc.user.sendInvitation.useMutation()

  // Mentor assignments (only fetched for mentors)
  const { data: mentorAssignments } = trpc.mentor.listAssignments.useQuery(
    { mentorId: userId, page: 1, perPage: 50 },
    { enabled: user?.role === 'MENTOR' }
  )

  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [role, setRole] = useState<string>('JURY_MEMBER')
  const [status, setStatus] = useState<string>('NONE')
  const [expertiseTags, setExpertiseTags] = useState<string[]>([])
  const [maxAssignments, setMaxAssignments] = useState<string>('')
  const [showSuperAdminConfirm, setShowSuperAdminConfirm] = useState(false)
  const [pendingSuperAdminRole, setPendingSuperAdminRole] = useState(false)

  useEffect(() => {
    if (user) {
      setName(user.name || '')
      setEmail(user.email || '')
      setRole(user.role)
      setStatus(user.status)
      setExpertiseTags(user.expertiseTags || [])
      setMaxAssignments(user.maxAssignments?.toString() || '')
    }
  }, [user])

  const handleSave = async () => {
    try {
      await updateUser.mutateAsync({
        id: userId,
        email: email || undefined,
        name: name || null,
        role: role as 'SUPER_ADMIN' | 'JURY_MEMBER' | 'MENTOR' | 'OBSERVER' | 'PROGRAM_ADMIN',
        status: status as 'NONE' | 'INVITED' | 'ACTIVE' | 'SUSPENDED',
        expertiseTags,
        maxAssignments: maxAssignments ? parseInt(maxAssignments) : null,
      })
      utils.user.get.invalidate({ id: userId })
      utils.user.list.invalidate()
      toast.success('Member updated successfully')
      router.push('/admin/members')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to update member')
    }
  }

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

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-9 w-32" />
        <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" />
          </CardContent>
        </Card>
      </div>
    )
  }

  if (error || !user) {
    return (
      <div className="space-y-6">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error Loading Member</AlertTitle>
          <AlertDescription>
            {error?.message || 'The member you\'re looking for does not exist.'}
            {process.env.NODE_ENV === 'development' && (
              <div className="mt-2 text-xs opacity-75">
                User ID: {userId}
              </div>
            )}
          </AlertDescription>
        </Alert>
        <Button asChild>
          <Link href="/admin/members">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Members
          </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/members">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Members
          </Link>
        </Button>
      </div>

      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            {user.name || 'Unnamed Member'}
          </h1>
          <div className="flex items-center gap-2 mt-1">
            <p className="text-muted-foreground">{user.email}</p>
            <Badge variant={user.status === 'ACTIVE' ? 'success' : user.status === 'SUSPENDED' ? 'destructive' : 'secondary'}>
              {user.status === 'NONE' ? 'Not Invited' : user.status}
            </Badge>
          </div>
        </div>
        {(user.status === 'NONE' || 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>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </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) => {
                  if (v === 'SUPER_ADMIN') {
                    setPendingSuperAdminRole(true)
                    setShowSuperAdminConfirm(true)
                  } else {
                    setRole(v)
                  }
                }}
                disabled={!isSuperAdmin && (user.role === 'SUPER_ADMIN' || user.role === 'PROGRAM_ADMIN')}
              >
                <SelectTrigger id="role">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {isSuperAdmin && (
                    <SelectItem value="SUPER_ADMIN">Super Admin</SelectItem>
                  )}
                  {isSuperAdmin && (
                    <SelectItem value="PROGRAM_ADMIN">Program Admin</SelectItem>
                  )}
                  <SelectItem value="JURY_MEMBER">Jury Member</SelectItem>
                  <SelectItem value="MENTOR">Mentor</SelectItem>
                  <SelectItem value="OBSERVER">Observer</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select value={status} onValueChange={setStatus}>
                <SelectTrigger id="status">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="NONE">Not Invited</SelectItem>
                  <SelectItem value="INVITED">Invited</SelectItem>
                  <SelectItem value="ACTIVE">Active</SelectItem>
                  <SelectItem value="SUSPENDED">Suspended</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Expertise & Capacity */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Shield className="h-5 w-5" />
              Expertise & Capacity
            </CardTitle>
          </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"
              />
            </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">Jury Assignments</p>
                    <p className="text-2xl font-semibold">{user._count.assignments}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">Mentor Assignments</p>
                    <p className="text-2xl font-semibold">{user._count.mentorAssignments}</p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Mentor Assignments Section */}
      {user.role === 'MENTOR' && mentorAssignments && mentorAssignments.assignments.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Mentored Projects</CardTitle>
            <CardDescription>
              Projects this mentor is assigned to
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Project</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Assigned</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {mentorAssignments.assignments.map((assignment) => (
                  <TableRow key={assignment.id}>
                    <TableCell>
                      <Link
                        href={`/admin/projects/${assignment.project.id}`}
                        className="font-medium hover:underline"
                      >
                        {assignment.project.title}
                      </Link>
                      {assignment.project.teamName && (
                        <p className="text-sm text-muted-foreground">
                          {assignment.project.teamName}
                        </p>
                      )}
                    </TableCell>
                    <TableCell>
                      {assignment.project.competitionCategory ? (
                        <Badge variant="outline">
                          {assignment.project.competitionCategory.replace('_', ' ')}
                        </Badge>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">
                        {assignment.project.status ?? 'SUBMITTED'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {new Date(assignment.assignedAt).toLocaleDateString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Activity Log */}
      <UserActivityLog userId={userId} />

      {/* Status Alert */}
      {user.status === 'NONE' && (
        <Alert>
          <Mail className="h-4 w-4" />
          <AlertTitle>Not Yet Invited</AlertTitle>
          <AlertDescription>
            This member was added to the platform via project import but hasn&apos;t been
            invited yet. Send them an invitation using the button above.
          </AlertDescription>
        </Alert>
      )}
      {user.status === 'INVITED' && (
        <Alert>
          <Mail className="h-4 w-4" />
          <AlertTitle>Invitation Pending</AlertTitle>
          <AlertDescription>
            This member 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/members">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>

      {/* Super Admin Confirmation Dialog */}
      <AlertDialog open={showSuperAdminConfirm} onOpenChange={setShowSuperAdminConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Grant Super Admin Access?</AlertDialogTitle>
            <AlertDialogDescription>
              This will grant <strong>{name || user?.name || 'this user'}</strong> full Super Admin
              access, including user management, system settings, and all administrative
              capabilities. This action should only be performed for trusted administrators.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setPendingSuperAdminRole(false)
              }}
            >
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                setRole('SUPER_ADMIN')
                setPendingSuperAdminRole(false)
                setShowSuperAdminConfirm(false)
              }}
              className="bg-red-600 hover:bg-red-700"
            >
              Confirm Super Admin
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
