'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 [targetStageId, setTargetStageId] = 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 }
  )

  // Get stages from the selected program (program.list includes rounds/stages)
  const { data: selectedProgramData, isLoading: isLoadingStages } = trpc.program.get.useQuery(
    { id: selectedProgramId },
    { enabled: !!selectedProgramId }
  )
  const stages = (selectedProgramData?.stages || []) as Array<{ id: string; name: string }>

  const utils = trpc.useUtils()
  const assignMutation = trpc.projectPool.assignToStage.useMutation({
    onSuccess: (result) => {
      utils.project.list.invalidate()
      utils.program.get.invalidate()
      toast.success(`Assigned ${result.assignedCount} project${result.assignedCount !== 1 ? 's' : ''} to stage`)
      setSelectedProjects([])
      setAssignDialogOpen(false)
      setTargetStageId('')
      refetch()
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to assign projects')
    },
  })

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

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

  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 stages
        </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">
                            {isLoadingStages ? (
                              <Skeleton className="h-9 w-[200px]" />
                            ) : (
                              <Select
                                onValueChange={(stageId) => handleQuickAssign(project.id, stageId)}
                                disabled={assignMutation.isPending}
                              >
                                <SelectTrigger className="w-[200px]">
                                  <SelectValue placeholder="Assign to stage..." />
                                </SelectTrigger>
                                <SelectContent>
                                  {stages?.map((stage: { id: string; name: string }) => (
                                    <SelectItem key={stage.id} value={stage.id}>
                                      {stage.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 Stage</DialogTitle>
            <DialogDescription>
              Assign {selectedProjects.length} selected project{selectedProjects.length > 1 ? 's' : ''} to:
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Select value={targetStageId} onValueChange={setTargetStageId}>
              <SelectTrigger>
                <SelectValue placeholder="Select stage..." />
              </SelectTrigger>
              <SelectContent>
                {stages?.map((stage: { id: string; name: string }) => (
                  <SelectItem key={stage.id} value={stage.id}>
                    {stage.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAssignDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleBulkAssign}
              disabled={!targetStageId || assignMutation.isPending}
            >
              {assignMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
