'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 { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Search, Loader2, Plus, Package } from 'lucide-react'
import { getCountryName } from '@/lib/countries'

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

export function AssignProjectsDialog({
  roundId,
  programId,
  open,
  onOpenChange,
  onSuccess,
}: AssignProjectsDialogProps) {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')

  const utils = trpc.useUtils()

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300)
    return () => clearTimeout(timer)
  }, [search])

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

  const { data, isLoading } = trpc.project.list.useQuery(
    {
      programId,
      notInRoundId: roundId,
      search: debouncedSearch || undefined,
      page: 1,
      perPage: 5000,
    },
    { enabled: open }
  )

  const assignMutation = trpc.round.assignProjects.useMutation({
    onSuccess: (result) => {
      toast.success(`${result.assigned} project${result.assigned !== 1 ? 's' : ''} assigned to 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 handleAssign = () => {
    if (selectedIds.size === 0) return
    assignMutation.mutate({
      roundId,
      projectIds: Array.from(selectedIds),
    })
  }

  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">
            <Plus className="h-5 w-5" />
            Assign Projects to Round
          </DialogTitle>
          <DialogDescription>
            Select projects from the program to add to this round.
          </DialogDescription>
        </DialogHeader>

        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search projects..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </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">
              <Package className="h-12 w-12 text-muted-foreground/50" />
              <p className="mt-2 font-medium">No available projects</p>
              <p className="text-sm text-muted-foreground">
                All program projects are already in this round.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <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>

              <div className="rounded-lg border max-h-[400px] overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12" />
                      <TableHead>Project</TableHead>
                      <TableHead>Team</TableHead>
                      <TableHead>Country</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>
                          {project.country ? (
                            <Badge variant="outline" className="text-xs">
                              {getCountryName(project.country)}
                            </Badge>
                          ) : '—'}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleAssign}
            disabled={selectedIds.size === 0 || assignMutation.isPending}
          >
            {assignMutation.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Plus className="mr-2 h-4 w-4" />
            )}
            Assign Selected ({selectedIds.size})
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
