'use client'

import { useState, useEffect, useMemo } from 'react'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { useEdition } from '@/contexts/edition-context'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Switch } from '@/components/ui/switch'
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, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { toast } from 'sonner'
import { ArrowLeft, ChevronLeft, ChevronRight, Loader2, X, Layers, Info } from 'lucide-react'

const roundTypeColors: Record<string, string> = {
  INTAKE: 'bg-gray-100 text-gray-700',
  FILTERING: 'bg-amber-100 text-amber-700',
  EVALUATION: 'bg-blue-100 text-blue-700',
  SUBMISSION: 'bg-purple-100 text-purple-700',
  MENTORING: 'bg-teal-100 text-teal-700',
  LIVE_FINAL: 'bg-red-100 text-red-700',
  DELIBERATION: 'bg-indigo-100 text-indigo-700',
}

export default function ProjectPoolPage() {
  const searchParams = useSearchParams()
  const { currentEdition, isLoading: editionLoading } = useEdition()

  // URL params for deep-linking context
  const urlRoundId = searchParams.get('roundId') || ''
  const urlCompetitionId = searchParams.get('competitionId') || ''

  // Auto-select programId from edition
  const programId = currentEdition?.id || ''

  const [selectedProjects, setSelectedProjects] = useState<string[]>([])
  const [assignDialogOpen, setAssignDialogOpen] = useState(false)
  const [assignAllDialogOpen, setAssignAllDialogOpen] = useState(false)
  const [targetRoundId, setTargetRoundId] = useState<string>(urlRoundId)
  const [searchQuery, setSearchQuery] = useState('')
  const [categoryFilter, setCategoryFilter] = useState<'STARTUP' | 'BUSINESS_CONCEPT' | 'all'>('all')
  const [showUnassignedOnly, setShowUnassignedOnly] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const perPage = 50

  // Pre-select target round from URL param
  useEffect(() => {
    if (urlRoundId) setTargetRoundId(urlRoundId)
  }, [urlRoundId])

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

  // Load rounds from program (flattened from all competitions, now with competitionId)
  const { data: programData, isLoading: isLoadingRounds } = trpc.program.get.useQuery(
    { id: programId },
    { enabled: !!programId }
  )

  // Get round name for context banner
  const allRounds = useMemo(() => {
    return (programData?.rounds || []) as Array<{
      id: string
      name: string
      competitionId: string
      status: string
      _count: { projects: number; assignments: number }
    }>
  }, [programData])

  // Filter rounds by competitionId if URL param is set
  const filteredRounds = useMemo(() => {
    if (urlCompetitionId) {
      return allRounds.filter((r) => r.competitionId === urlCompetitionId)
    }
    return allRounds
  }, [allRounds, urlCompetitionId])

  const contextRound = urlRoundId ? allRounds.find((r) => r.id === urlRoundId) : null

  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(urlRoundId)
      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(urlRoundId)
      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 || !programId) return
    assignAllMutation.mutate({
      programId,
      roundId: targetRoundId,
      competitionCategory: categoryFilter === 'all' ? undefined : categoryFilter,
      unassignedOnly: showUnassignedOnly,
    })
  }

  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])
    }
  }

  if (editionLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-10 w-64" />
        <Skeleton className="h-20 w-full" />
        <Skeleton className="h-96 w-full" />
      </div>
    )
  }

  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 className="flex-1">
          <h1 className="text-2xl font-semibold">Project Pool</h1>
          <p className="text-muted-foreground">
            {currentEdition
              ? `${currentEdition.name} ${currentEdition.year} \u2014 ${poolData?.total ?? '...'} projects`
              : 'No edition selected'}
          </p>
        </div>
      </div>

      {/* Context banner when coming from a round */}
      {contextRound && (
        <Card className="border-blue-200 bg-blue-50/50">
          <CardContent className="py-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Info className="h-4 w-4 text-blue-600 shrink-0" />
                <p className="text-sm">
                  Assigning to <span className="font-semibold">{contextRound.name}</span>
                  {' \u2014 '}
                  <span className="text-muted-foreground">
                    projects already in this round are hidden
                  </span>
                </p>
              </div>
              <Link
                href={`/admin/rounds/${urlRoundId}` as Route}
              >
                <Button variant="outline" size="sm" className="shrink-0">
                  <ArrowLeft className="h-3.5 w-3.5 mr-1" />
                  Back to Round
                </Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 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">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 className="flex items-center gap-2 pb-0.5">
            <Switch
              id="unassigned-only"
              checked={showUnassignedOnly}
              onCheckedChange={(checked) => {
                setShowUnassignedOnly(checked)
                setCurrentPage(1)
              }}
            />
            <label htmlFor="unassigned-only" className="text-sm font-medium cursor-pointer whitespace-nowrap">
              Unassigned only
            </label>
          </div>
        </div>
      </Card>

      {/* Action bar */}
      {programId && poolData && poolData.total > 0 && (
        <div className="flex items-center justify-between flex-wrap gap-2">
          <p className="text-sm text-muted-foreground">
            <span className="font-medium text-foreground">{poolData.total}</span> project{poolData.total !== 1 ? 's' : ''}
            {showUnassignedOnly && ' (unassigned only)'}
          </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 */}
      {programId ? (
        <>
          {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 w-[40px]">
                          <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">Rounds</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" className="text-xs">
                                {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
                              </Badge>
                            )}
                          </td>
                          <td className="p-3">
                            {(project as any).projectRoundStates?.length > 0 ? (
                              <div className="flex flex-wrap gap-1">
                                {(project as any).projectRoundStates.map((prs: any) => (
                                  <Badge
                                    key={prs.roundId}
                                    variant="secondary"
                                    className={`text-[10px] ${roundTypeColors[prs.round?.roundType] || 'bg-gray-100 text-gray-700'}`}
                                  >
                                    {prs.round?.name || 'Round'}
                                  </Badge>
                                ))}
                              </div>
                            ) : (
                              <span className="text-xs text-muted-foreground">None</span>
                            )}
                          </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>
                                  {filteredRounds.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">
              <div className="flex flex-col items-center gap-3">
                <Layers className="h-8 w-8 text-muted-foreground/50" />
                <p>
                  {showUnassignedOnly
                    ? 'No unassigned projects found'
                    : urlRoundId
                      ? 'All projects are already assigned to this round'
                      : 'No projects found for this program'}
                </p>
              </div>
            </Card>
          )}
        </>
      ) : (
        <Card className="p-8 text-center text-muted-foreground">
          No edition selected. Please select an edition from the sidebar.
        </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>
                {filteredRounds.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 Projects</DialogTitle>
            <DialogDescription>
              This will assign all {poolData?.total || 0}{categoryFilter !== 'all' ? ` ${categoryFilter === 'STARTUP' ? 'Startup' : 'Business Concept'}` : ''}{showUnassignedOnly ? ' 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>
                {filteredRounds.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>
  )
}
