'use client'

import { useState, useCallback, useEffect } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Minus, Loader2, AlertTriangle } from 'lucide-react'

interface RemoveProjectsDialogProps {
  roundId: string
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess?: () => void
}

export function RemoveProjectsDialog({
  roundId,
  open,
  onOpenChange,
  onSuccess,
}: RemoveProjectsDialogProps) {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [confirmOpen, setConfirmOpen] = useState(false)

  const utils = trpc.useUtils()

  // Reset state when dialog opens
  useEffect(() => {
    if (open) {
      setSelectedIds(new Set())
      setConfirmOpen(false)
    }
  }, [open])

  const { data, isLoading } = trpc.project.list.useQuery(
    { roundId, page: 1, perPage: 5000 },
    { enabled: open }
  )

  const removeMutation = trpc.round.removeProjects.useMutation({
    onSuccess: (result) => {
      toast.success(
        `${result.removed} project${result.removed !== 1 ? 's' : ''} removed from round`
      )
      utils.round.get.invalidate({ id: roundId })
      utils.project.list.invalidate()
      onSuccess?.()
      onOpenChange(false)
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  const projects = data?.projects ?? []

  const toggleProject = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }, [])

  const toggleAll = useCallback(() => {
    if (selectedIds.size === projects.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(projects.map((p) => p.id)))
    }
  }, [selectedIds.size, projects])

  const handleRemove = () => {
    if (selectedIds.size === 0) return
    removeMutation.mutate({
      roundId,
      projectIds: Array.from(selectedIds),
    })
    setConfirmOpen(false)
  }

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Minus className="h-5 w-5" />
              Remove Projects from Round
            </DialogTitle>
            <DialogDescription>
              Select projects to remove from this round. The projects will remain
              in the program and can be re-assigned later.
            </DialogDescription>
          </DialogHeader>

          <div className="flex items-start gap-2 rounded-lg bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/50 dark:text-amber-200">
            <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
            <span>
              Removing projects from a round will also delete their jury
              assignments and evaluations in this round.
            </span>
          </div>

          <div className="flex-1 min-h-0 overflow-hidden">
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : projects.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <p className="font-medium">No projects in this round</p>
                <p className="text-sm text-muted-foreground">
                  There are no projects to remove.
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <Checkbox
                    checked={selectedIds.size === projects.length && projects.length > 0}
                    onCheckedChange={toggleAll}
                  />
                  <span className="text-sm text-muted-foreground">
                    {selectedIds.size} of {projects.length} selected
                  </span>
                </div>

                <div className="rounded-lg border max-h-[350px] overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-12" />
                        <TableHead>Project</TableHead>
                        <TableHead>Team</TableHead>
                        <TableHead>Status</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {projects.map((project) => (
                        <TableRow
                          key={project.id}
                          className={selectedIds.has(project.id) ? 'bg-muted/50' : 'cursor-pointer'}
                          onClick={() => toggleProject(project.id)}
                        >
                          <TableCell>
                            <Checkbox
                              checked={selectedIds.has(project.id)}
                              onCheckedChange={() => toggleProject(project.id)}
                              onClick={(e) => e.stopPropagation()}
                            />
                          </TableCell>
                          <TableCell className="font-medium">
                            {project.title}
                          </TableCell>
                          <TableCell className="text-muted-foreground">
                            {project.teamName || '—'}
                          </TableCell>
                          <TableCell>
                            <Badge variant="secondary" className="text-xs">
                              {(project.status ?? 'SUBMITTED').replace('_', ' ')}
                            </Badge>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => setConfirmOpen(true)}
              disabled={selectedIds.size === 0 || removeMutation.isPending}
            >
              {removeMutation.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Minus className="mr-2 h-4 w-4" />
              )}
              Remove Selected ({selectedIds.size})
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirm Removal</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to remove {selectedIds.size} project
              {selectedIds.size !== 1 ? 's' : ''} from this round? Their
              assignments and evaluations in this round will be deleted. The
              projects will remain in the program.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleRemove}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Remove Projects
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
