'use client'

import { useParams } from 'next/navigation'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { ArrowLeft, Plus, UserMinus } from 'lucide-react'
import { toast } from 'sonner'

export default function ProjectAssignmentsPage() {
  const params = useParams()
  const id = params.id as string

  const { data: project, isLoading: projectLoading } = trpc.project.get.useQuery({ id })
  const { data: assignments = [], isLoading: assignmentsLoading } = trpc.assignment.listByProject.useQuery({ projectId: id })

  const utils = trpc.useUtils()

  const removeAssignment = trpc.assignment.delete.useMutation({
    onSuccess: () => {
      toast.success('Assignment removed')
      utils.assignment.listByProject.invalidate({ projectId: id })
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to remove assignment')
    },
  })

  // Remove handled via AlertDialog in JSX

  const isLoading = projectLoading || assignmentsLoading

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-10 w-10" />
          <div className="space-y-2">
            <Skeleton className="h-8 w-64" />
            <Skeleton className="h-4 w-32" />
          </div>
        </div>
        <Card>
          <CardContent className="space-y-4 pt-6">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href={`/admin/projects/${id}`}>
            <Button variant="ghost" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl font-bold">Jury Assignments</h1>
            <p className="text-muted-foreground">
              {project?.title}
            </p>
          </div>
        </div>
        <Button asChild>
          <Link href={`/admin/rounds/${project?.roundId}/assignments`}>
            <Plus className="mr-2 h-4 w-4" />
            Manage in Round
          </Link>
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Assigned Jury Members</CardTitle>
          <CardDescription>
            {assignments.length} jury member{assignments.length !== 1 ? 's' : ''} assigned to evaluate this project
          </CardDescription>
        </CardHeader>
        <CardContent>
          {assignments.length === 0 ? (
            <div className="py-8 text-center text-muted-foreground">
              No jury members assigned yet.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Jury Member</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {assignments.map((assignment) => (
                  <TableRow key={assignment.id}>
                    <TableCell>
                      <div>
                        <p className="font-medium">{assignment.user.name}</p>
                        <p className="text-sm text-muted-foreground">{assignment.user.email}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={assignment.evaluation?.status === 'SUBMITTED' ? 'success' : 'secondary'}>
                        {assignment.evaluation?.status || 'Pending'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            disabled={removeAssignment.isPending}
                          >
                            <UserMinus className="h-4 w-4" />
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>Remove Assignment</AlertDialogTitle>
                            <AlertDialogDescription>
                              Remove this jury member from the project? Their evaluation data will also be deleted.
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction onClick={() => removeAssignment.mutate({ id: assignment.id })}>
                              Remove
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
