'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Card } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { toast } from 'sonner'
import { ArrowLeft, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'

export default function ProjectPoolPage() {
  const [selectedProgramId, setSelectedProgramId] = useState<string>('')
  const [selectedProjects, setSelectedProjects] = useState<string[]>([])
  const [assignDialogOpen, setAssignDialogOpen] = useState(false)
  const [assignAllDialogOpen, setAssignAllDialogOpen] = useState(false)
  const [targetRoundId, setTargetRoundId] = useState<string>('')
  const [searchQuery, setSearchQuery] = useState('')
  const [categoryFilter, setCategoryFilter] = useState<'STARTUP' | 'BUSINESS_CONCEPT' | 'all'>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const perPage = 50

  const { data: programs } = trpc.program.list.useQuery({ status: 'ACTIVE' })

  const { data: poolData, isLoading: isLoadingPool, refetch } = trpc.projectPool.listUnassigned.useQuery(
    {
      programId: selectedProgramId,
      competitionCategory: categoryFilter === 'all' ? undefined : categoryFilter,
      search: searchQuery || undefined,
      page: currentPage,
      perPage,
    },
    { enabled: !!selectedProgramId }
  )

  // Load rounds from program (program.get returns rounds from all competitions)
  const { data: programData, isLoading: isLoadingRounds } = trpc.program.get.useQuery(
    { id: selectedProgramId },
    { enabled: !!selectedProgramId }
  )
  const rounds = (programData?.rounds || []) as Array<{ id: string; name: string; roundType: string; sortOrder: number }>

  const utils = trpc.useUtils()

  const assignMutation = trpc.projectPool.assignToRound.useMutation({
    onSuccess: (result) => {
      utils.project.list.invalidate()
      utils.projectPool.listUnassigned.invalidate()
      toast.success(`Assigned ${result.assignedCount} project${result.assignedCount !== 1 ? 's' : ''} to round`)
      setSelectedProjects([])
      setAssignDialogOpen(false)
      setTargetRoundId('')
      refetch()
    },
    onError: (error: unknown) => {
      toast.error((error as { message?: string }).message || 'Failed to assign projects')
    },
  })

  const assignAllMutation = trpc.projectPool.assignAllToRound.useMutation({
    onSuccess: (result) => {
      utils.project.list.invalidate()
      utils.projectPool.listUnassigned.invalidate()
      toast.success(`Assigned all ${result.assignedCount} projects to round`)
      setSelectedProjects([])
      setAssignAllDialogOpen(false)
      setTargetRoundId('')
      refetch()
    },
    onError: (error: unknown) => {
      toast.error((error as { message?: string }).message || 'Failed to assign projects')
    },
  })

  const isPending = assignMutation.isPending || assignAllMutation.isPending

  const handleBulkAssign = () => {
    if (selectedProjects.length === 0 || !targetRoundId) return
    assignMutation.mutate({
      projectIds: selectedProjects,
      roundId: targetRoundId,
    })
  }

  const handleAssignAll = () => {
    if (!targetRoundId || !selectedProgramId) return
    assignAllMutation.mutate({
      programId: selectedProgramId,
      roundId: targetRoundId,
      competitionCategory: categoryFilter === 'all' ? undefined : categoryFilter,
    })
  }

  const handleQuickAssign = (projectId: string, roundId: string) => {
    assignMutation.mutate({
      projectIds: [projectId],
      roundId,
    })
  }

  const toggleSelectAll = () => {
    if (!poolData?.projects) return
    if (selectedProjects.length === poolData.projects.length) {
      setSelectedProjects([])
    } else {
      setSelectedProjects(poolData.projects.map((p) => p.id))
    }
  }

  const toggleSelectProject = (projectId: string) => {
    if (selectedProjects.includes(projectId)) {
      setSelectedProjects(selectedProjects.filter((id) => id !== projectId))
    } else {
      setSelectedProjects([...selectedProjects, projectId])
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-3">
        <Link href={"/admin/projects" as Route} className="mt-1 shrink-0">
          <Button variant="ghost" size="icon" className="h-8 w-8">
            <ArrowLeft className="h-4 w-4" />
          </Button>
        </Link>
        <div>
          <h1 className="text-2xl font-semibold">Project Pool</h1>
          <p className="text-muted-foreground">
            Assign unassigned projects to competition rounds
          </p>
        </div>
      </div>

      {/* Filters */}
      <Card className="p-4">
        <div className="flex flex-col gap-4 md:flex-row md:items-end">
          <div className="flex-1 space-y-2">
            <label className="text-sm font-medium">Program</label>
            <Select value={selectedProgramId} onValueChange={(value) => {
              setSelectedProgramId(value)
              setSelectedProjects([])
              setCurrentPage(1)
            }}>
              <SelectTrigger>
                <SelectValue placeholder="Select program..." />
              </SelectTrigger>
              <SelectContent>
                {programs?.map((program) => (
                  <SelectItem key={program.id} value={program.id}>
                    {program.name} {program.year}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex-1 space-y-2">
            <label className="text-sm font-medium">Category</label>
            <Select value={categoryFilter} onValueChange={(value: string) => {
              setCategoryFilter(value as 'STARTUP' | 'BUSINESS_CONCEPT' | 'all')
              setCurrentPage(1)
            }}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Categories</SelectItem>
                <SelectItem value="STARTUP">Startup</SelectItem>
                <SelectItem value="BUSINESS_CONCEPT">Business Concept</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex-1 space-y-2">
            <label className="text-sm font-medium">Search</label>
            <Input
              placeholder="Project or team name..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value)
                setCurrentPage(1)
              }}
            />
          </div>
        </div>
      </Card>

      {/* Action bar */}
      {selectedProgramId && poolData && poolData.total > 0 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            <span className="font-medium text-foreground">{poolData.total}</span> unassigned project{poolData.total !== 1 ? 's' : ''}
          </p>
          <div className="flex items-center gap-2">
            {selectedProjects.length > 0 && (
              <Button onClick={() => setAssignDialogOpen(true)} size="sm">
                Assign {selectedProjects.length} Selected
              </Button>
            )}
            <Button
              variant="default"
              size="sm"
              onClick={() => setAssignAllDialogOpen(true)}
            >
              Assign All {poolData.total} to Round
            </Button>
          </div>
        </div>
      )}

      {/* Projects Table */}
      {selectedProgramId && (
        <>
          {isLoadingPool ? (
            <Card className="p-4">
              <div className="space-y-3">
                {[...Array(5)].map((_, i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            </Card>
          ) : poolData && poolData.total > 0 ? (
            <>
              <Card>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="border-b">
                      <tr className="text-sm">
                        <th className="p-3 text-left">
                          <Checkbox
                            checked={poolData.projects.length > 0 && selectedProjects.length === poolData.projects.length}
                            onCheckedChange={toggleSelectAll}
                          />
                        </th>
                        <th className="p-3 text-left font-medium">Project</th>
                        <th className="p-3 text-left font-medium">Category</th>
                        <th className="p-3 text-left font-medium">Country</th>
                        <th className="p-3 text-left font-medium">Submitted</th>
                        <th className="p-3 text-left font-medium">Quick Assign</th>
                      </tr>
                    </thead>
                    <tbody>
                      {poolData.projects.map((project) => (
                        <tr key={project.id} className="border-b hover:bg-muted/50">
                          <td className="p-3">
                            <Checkbox
                              checked={selectedProjects.includes(project.id)}
                              onCheckedChange={() => toggleSelectProject(project.id)}
                            />
                          </td>
                          <td className="p-3">
                            <Link
                              href={`/admin/projects/${project.id}` as Route}
                              className="hover:underline"
                            >
                              <div className="font-medium">{project.title}</div>
                              <div className="text-sm text-muted-foreground">{project.teamName}</div>
                            </Link>
                          </td>
                          <td className="p-3">
                            {project.competitionCategory && (
                              <Badge variant="outline">
                                {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
                              </Badge>
                            )}
                          </td>
                          <td className="p-3 text-sm text-muted-foreground">
                            {project.country || '-'}
                          </td>
                          <td className="p-3 text-sm text-muted-foreground">
                            {project.submittedAt
                              ? new Date(project.submittedAt).toLocaleDateString()
                              : '-'}
                          </td>
                          <td className="p-3">
                            {isLoadingRounds ? (
                              <Skeleton className="h-9 w-[200px]" />
                            ) : (
                              <Select
                                onValueChange={(roundId) => handleQuickAssign(project.id, roundId)}
                                disabled={isPending}
                              >
                                <SelectTrigger className="w-[200px]">
                                  <SelectValue placeholder="Assign to round..." />
                                </SelectTrigger>
                                <SelectContent>
                                  {rounds.map((round) => (
                                    <SelectItem key={round.id} value={round.id}>
                                      {round.name}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Card>

              {/* Pagination */}
              {poolData.totalPages > 1 && (
                <div className="flex items-center justify-between">
                  <p className="text-sm text-muted-foreground">
                    Showing {((currentPage - 1) * perPage) + 1} to {Math.min(currentPage * perPage, poolData.total)} of {poolData.total}
                  </p>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(currentPage - 1)}
                      disabled={currentPage === 1}
                    >
                      <ChevronLeft className="h-4 w-4" />
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(currentPage + 1)}
                      disabled={currentPage === poolData.totalPages}
                    >
                      Next
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <Card className="p-8 text-center text-muted-foreground">
              No unassigned projects found for this program
            </Card>
          )}
        </>
      )}

      {!selectedProgramId && (
        <Card className="p-8 text-center text-muted-foreground">
          Select a program to view unassigned projects
        </Card>
      )}

      {/* Bulk Assignment Dialog (selected projects) */}
      <Dialog open={assignDialogOpen} onOpenChange={setAssignDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Assign Selected Projects</DialogTitle>
            <DialogDescription>
              Assign {selectedProjects.length} selected project{selectedProjects.length > 1 ? 's' : ''} to a round:
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Select value={targetRoundId} onValueChange={setTargetRoundId}>
              <SelectTrigger>
                <SelectValue placeholder="Select round..." />
              </SelectTrigger>
              <SelectContent>
                {rounds.map((round) => (
                  <SelectItem key={round.id} value={round.id}>
                    {round.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAssignDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleBulkAssign}
              disabled={!targetRoundId || isPending}
            >
              {assignMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign {selectedProjects.length} Projects
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Assign ALL Dialog */}
      <Dialog open={assignAllDialogOpen} onOpenChange={setAssignAllDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Assign All Unassigned Projects</DialogTitle>
            <DialogDescription>
              This will assign all {poolData?.total || 0}{categoryFilter !== 'all' ? ` ${categoryFilter === 'STARTUP' ? 'Startup' : 'Business Concept'}` : ''} unassigned projects to a round in one operation.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Select value={targetRoundId} onValueChange={setTargetRoundId}>
              <SelectTrigger>
                <SelectValue placeholder="Select round..." />
              </SelectTrigger>
              <SelectContent>
                {rounds.map((round) => (
                  <SelectItem key={round.id} value={round.id}>
                    {round.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAssignAllDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleAssignAll}
              disabled={!targetRoundId || isPending}
            >
              {assignAllMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign All {poolData?.total || 0} Projects
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
