'use client'

import { useState } from 'react'
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 { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'
import Link from 'next/link'

export default function ProjectPoolPage() {
  const [selectedProgramId, setSelectedProgramId] = useState<string>('')
  const [selectedProjects, setSelectedProjects] = useState<string[]>([])
  const [assignDialogOpen, setAssignDialogOpen] = 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 }
  )

  const { data: rounds, isLoading: isLoadingRounds } = trpc.round.listByProgram.useQuery(
    { programId: selectedProgramId },
    { enabled: !!selectedProgramId }
  )

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

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

  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>
        <h1 className="text-2xl font-semibold">Project Pool</h1>
        <p className="text-muted-foreground">
          Assign unassigned projects to evaluation rounds
        </p>
      </div>

      {/* Program Selector */}
      <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: any) => {
              setCategoryFilter(value)
              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>

          {selectedProjects.length > 0 && (
            <Button onClick={() => setAssignDialogOpen(true)} className="whitespace-nowrap">
              Assign {selectedProjects.length} Project{selectedProjects.length > 1 ? 's' : ''}
            </Button>
          )}
        </div>
      </Card>

      {/* 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={selectedProjects.length === poolData.projects.length && poolData.projects.length > 0}
                            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">Action</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}`}
                              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">
                            <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={assignMutation.isPending}
                              >
                                <SelectTrigger className="w-[200px]">
                                  <SelectValue placeholder="Assign to round..." />
                                </SelectTrigger>
                                <SelectContent>
                                  {rounds?.map((round: { id: string; name: string; sortOrder: number }) => (
                                    <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} projects
                  </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 */}
      <Dialog open={assignDialogOpen} onOpenChange={setAssignDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Assign Projects to Round</DialogTitle>
            <DialogDescription>
              Assign {selectedProjects.length} selected project{selectedProjects.length > 1 ? 's' : ''} to:
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Select value={targetRoundId} onValueChange={setTargetRoundId}>
              <SelectTrigger>
                <SelectValue placeholder="Select round..." />
              </SelectTrigger>
              <SelectContent>
                {rounds?.map((round: { id: string; name: string; sortOrder: number }) => (
                  <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 || assignMutation.isPending}
            >
              {assignMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
