'use client'

import { useState, useEffect, useMemo } from 'react'
import {
  AlertTriangle,
  Bot,
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  Loader2,
  Plus,
  Sparkles,
  Tag,
  User,
  X,
} from 'lucide-react'
import { toast } from 'sonner'
import { trpc } from '@/lib/trpc/client'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'

type EditableAssignment = {
  localId: string
  userId: string
  userName: string
  projectId: string
  projectTitle: string
  score: number
  reasoning: string[]
  matchingTags: string[]
  policyViolations: string[]
  fromIntent: boolean
  isManual: boolean
}

type AssignmentPreviewSheetProps = {
  roundId: string
  open: boolean
  onOpenChange: (open: boolean) => void
  requiredReviews?: number
}

export function AssignmentPreviewSheet({
  roundId,
  open,
  onOpenChange,
  requiredReviews = 3,
}: AssignmentPreviewSheetProps) {
  const utils = trpc.useUtils()

  const [assignments, setAssignments] = useState<EditableAssignment[]>([])
  const [initialized, setInitialized] = useState(false)
  const [expandedJurors, setExpandedJurors] = useState<Set<string>>(new Set())
  const [addJurorId, setAddJurorId] = useState<string>('')
  const [addProjectId, setAddProjectId] = useState<string>('')

  // ── Queries ──────────────────────────────────────────────────────────────
  const {
    data: preview,
    isLoading,
    refetch,
  } = trpc.roundAssignment.preview.useQuery(
    { roundId, honorIntents: true, requiredReviews },
    { enabled: open },
  )

  // Fetch round data for jury group members
  const { data: round } = trpc.round.getById.useQuery(
    { id: roundId },
    { enabled: open },
  )

  // Fetch projects in this round
  const { data: projectStates } = trpc.roundEngine.getProjectStates.useQuery(
    { roundId },
    { enabled: open },
  )

  // Fetch existing assignments to exclude already-assigned pairs
  const { data: existingAssignments } = trpc.assignment.listByStage.useQuery(
    { roundId },
    { enabled: open },
  )

  const { mutate: execute, isPending: isExecuting } =
    trpc.roundAssignment.execute.useMutation({
      onSuccess: (result) => {
        toast.success(`Created ${result.created} assignments`)
        utils.roundAssignment.coverageReport.invalidate({ roundId })
        utils.roundAssignment.unassignedQueue.invalidate({ roundId })
        utils.assignment.listByStage.invalidate({ roundId })
        utils.roundEngine.getProjectStates.invalidate({ roundId })
        onOpenChange(false)
      },
      onError: (err) => {
        toast.error(err.message)
      },
    })

  // ── Initialize local state from preview ──────────────────────────────────
  useEffect(() => {
    if (preview && !initialized) {
      const mapped: EditableAssignment[] = preview.assignments.map(
        (a: any, idx: number) => ({
          localId: `ai-${idx}`,
          userId: a.userId,
          userName: a.userName,
          projectId: a.projectId,
          projectTitle: a.projectTitle,
          score: a.score,
          reasoning: a.reasoning ?? [],
          matchingTags: a.matchingTags ?? [],
          policyViolations: a.policyViolations ?? [],
          fromIntent: a.fromIntent ?? false,
          isManual: false,
        }),
      )
      setAssignments(mapped)
      // Auto-expand all jurors
      const jurorIds = new Set(mapped.map((a) => a.userId))
      setExpandedJurors(jurorIds)
      setInitialized(true)
    }
  }, [preview, initialized])

  // Reset when sheet closes
  useEffect(() => {
    if (!open) {
      setInitialized(false)
      setAssignments([])
      setExpandedJurors(new Set())
      setAddJurorId('')
      setAddProjectId('')
    }
  }, [open])

  // ── Derived data ─────────────────────────────────────────────────────────
  const juryMembers = useMemo(() => {
    if (!round?.juryGroup?.members) return []
    return round.juryGroup.members.map((m: any) => ({
      userId: m.userId,
      name: m.user?.name ?? m.userId,
      role: m.role,
    }))
  }, [round])

  const projects = useMemo((): Array<{ id: string; title: string; category?: string }> => {
    if (!projectStates) return []
    return projectStates.map((ps: any) => ({
      id: ps.project?.id ?? ps.projectId,
      title: ps.project?.title ?? ps.projectId,
      category: ps.project?.competitionCategory,
    }))
  }, [projectStates])

  // Build set of existing assignment pairs (already committed)
  const existingPairs = useMemo(() => {
    const pairs = new Set<string>()
    for (const a of existingAssignments ?? []) {
      pairs.add(`${a.userId}:${a.projectId}`)
    }
    return pairs
  }, [existingAssignments])

  // Build set of current preview assignment pairs
  const currentPairs = useMemo(() => {
    const pairs = new Set<string>()
    for (const a of assignments) {
      pairs.add(`${a.userId}:${a.projectId}`)
    }
    return pairs
  }, [assignments])

  // Group assignments by juror
  const groupedByJuror = useMemo(() => {
    const map = new Map<
      string,
      { userId: string; userName: string; assignments: EditableAssignment[] }
    >()
    for (const a of assignments) {
      if (!map.has(a.userId)) {
        map.set(a.userId, { userId: a.userId, userName: a.userName, assignments: [] })
      }
      map.get(a.userId)!.assignments.push(a)
    }
    return Array.from(map.values()).sort((a, b) =>
      b.assignments.length - a.assignments.length,
    )
  }, [assignments])

  // Stats
  const totalAssignments = assignments.length
  const uniqueProjects = new Set(assignments.map((a) => a.projectId)).size
  const uniqueJurors = new Set(assignments.map((a) => a.userId)).size
  const manualCount = assignments.filter((a) => a.isManual).length
  const removedCount = (preview?.stats.assignmentsGenerated ?? 0) - assignments.filter((a) => !a.isManual).length

  // Projects available for a specific juror (not already assigned in preview or existing)
  const getAvailableProjectsForJuror = (userId: string) => {
    return projects.filter((p) => {
      const pairKey = `${userId}:${p.id}`
      return !currentPairs.has(pairKey) && !existingPairs.has(pairKey)
    })
  }

  // ── Actions ──────────────────────────────────────────────────────────────
  const removeAssignment = (localId: string) => {
    setAssignments((prev) => prev.filter((a) => a.localId !== localId))
  }

  const addAssignment = () => {
    if (!addJurorId || !addProjectId) {
      toast.error('Select both a juror and a project')
      return
    }

    const juror = juryMembers.find((m) => m.userId === addJurorId)
    const project = projects.find((p) => p.id === addProjectId)
    if (!juror || !project) return

    const pairKey = `${addJurorId}:${addProjectId}`
    if (currentPairs.has(pairKey) || existingPairs.has(pairKey)) {
      toast.error('This assignment already exists')
      return
    }

    setAssignments((prev) => [
      ...prev,
      {
        localId: `manual-${Date.now()}`,
        userId: addJurorId,
        userName: juror.name,
        projectId: addProjectId,
        projectTitle: project.title,
        score: 0,
        reasoning: ['Manually added by admin'],
        matchingTags: [],
        policyViolations: [],
        fromIntent: false,
        isManual: true,
      },
    ])

    // Expand the juror's section
    setExpandedJurors((prev) => new Set([...prev, addJurorId]))
    setAddProjectId('')
  }

  const addProjectToJuror = (userId: string, projectId: string) => {
    const juror = juryMembers.find((m) => m.userId === userId)
    const project = projects.find((p) => p.id === projectId)
    if (!juror || !project) return

    setAssignments((prev) => [
      ...prev,
      {
        localId: `manual-${Date.now()}`,
        userId,
        userName: juror.name,
        projectId,
        projectTitle: project.title,
        score: 0,
        reasoning: ['Manually added by admin'],
        matchingTags: [],
        policyViolations: [],
        fromIntent: false,
        isManual: true,
      },
    ])
  }

  const toggleJuror = (userId: string) => {
    setExpandedJurors((prev) => {
      const next = new Set(prev)
      if (next.has(userId)) next.delete(userId)
      else next.add(userId)
      return next
    })
  }

  const handleExecute = () => {
    if (assignments.length === 0) {
      toast.error('No assignments to execute')
      return
    }

    execute({
      roundId,
      assignments: assignments.map((a) => ({
        userId: a.userId,
        projectId: a.projectId,
      })),
    })
  }

  // ── Render ───────────────────────────────────────────────────────────────
  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-2xl p-0 flex flex-col">
        <SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
          <SheetTitle className="text-lg">Assignment Preview</SheetTitle>
          <SheetDescription className="flex flex-wrap items-center gap-2 text-sm">
            <Badge variant="outline" className="text-xs gap-1 shrink-0">
              <Bot className="h-3 w-3" />
              AI Suggested
            </Badge>
            Review and fine-tune before executing.
          </SheetDescription>
        </SheetHeader>

        <ScrollArea className="flex-1 min-h-0">
          <div className="px-6 py-4 space-y-4">
            {isLoading ? (
              <div className="space-y-3">
                {[1, 2, 3, 4].map((i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : preview ? (
              <>
                {/* ── Summary stats ── */}
                <div className="grid grid-cols-4 gap-2">
                  {[
                    { label: 'Assignments', value: totalAssignments },
                    { label: 'Projects', value: uniqueProjects },
                    { label: 'Jurors', value: uniqueJurors },
                    { label: 'Unassigned', value: Math.max(0, (preview.stats.totalProjects ?? 0) - uniqueProjects) },
                  ].map((stat) => (
                    <div
                      key={stat.label}
                      className="rounded-lg border bg-muted/30 px-3 py-2 text-center"
                    >
                      <p className="text-lg font-bold tabular-nums">{stat.value}</p>
                      <p className="text-[11px] text-muted-foreground">{stat.label}</p>
                    </div>
                  ))}
                </div>

                {/* Modification indicator */}
                {(manualCount > 0 || removedCount > 0) && (
                  <div className="flex flex-wrap gap-2 text-xs">
                    {manualCount > 0 && (
                      <Badge variant="secondary" className="gap-1">
                        <Plus className="h-3 w-3" />
                        {manualCount} added manually
                      </Badge>
                    )}
                    {removedCount > 0 && (
                      <Badge variant="secondary" className="gap-1 text-red-600">
                        <X className="h-3 w-3" />
                        {removedCount} removed
                      </Badge>
                    )}
                  </div>
                )}

                {/* ── Warnings ── */}
                {preview.warnings && preview.warnings.length > 0 && (
                  <Card className="border-amber-300 bg-amber-50/50 dark:bg-amber-950/20">
                    <CardContent className="p-3">
                      <div className="flex items-start gap-2">
                        <AlertTriangle className="h-4 w-4 text-amber-600 mt-0.5 shrink-0" />
                        <div className="space-y-1">
                          {preview.warnings.map((w: string, idx: number) => (
                            <p key={idx} className="text-xs text-amber-800 dark:text-amber-200">
                              {w}
                            </p>
                          ))}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* ── Juror groups ── */}
                <div className="space-y-2">
                  <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Assignments by Juror
                  </h3>
                  {groupedByJuror.length === 0 ? (
                    <Card>
                      <CardContent className="py-8 text-center text-sm text-muted-foreground">
                        No assignments. Add some manually below.
                      </CardContent>
                    </Card>
                  ) : (
                    groupedByJuror.map((group) => (
                      <JurorGroup
                        key={group.userId}
                        group={group}
                        expanded={expandedJurors.has(group.userId)}
                        onToggle={() => toggleJuror(group.userId)}
                        onRemove={removeAssignment}
                        onAddProject={(projectId) =>
                          addProjectToJuror(group.userId, projectId)
                        }
                        availableProjects={getAvailableProjectsForJuror(group.userId)}
                        requiredReviews={requiredReviews}
                      />
                    ))
                  )}
                </div>

                {/* ── Add assignment manually ── */}
                <Card>
                  <CardHeader className="pb-2 pt-3 px-3">
                    <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <Plus className="h-3.5 w-3.5" />
                      Add Assignment
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="px-3 pb-3">
                    <div className="flex flex-col sm:flex-row gap-2">
                      <Select value={addJurorId} onValueChange={setAddJurorId}>
                        <SelectTrigger className="flex-1 h-9 text-xs">
                          <SelectValue placeholder="Select juror..." />
                        </SelectTrigger>
                        <SelectContent>
                          {juryMembers.map((m) => {
                            const load = assignments.filter(
                              (a) => a.userId === m.userId,
                            ).length
                            return (
                              <SelectItem key={m.userId} value={m.userId}>
                                <span className="flex items-center gap-2">
                                  <span className="truncate">{m.name}</span>
                                  <span className="text-muted-foreground text-[10px] shrink-0">
                                    ({load} assigned)
                                  </span>
                                </span>
                              </SelectItem>
                            )
                          })}
                        </SelectContent>
                      </Select>
                      <Select
                        value={addProjectId}
                        onValueChange={setAddProjectId}
                        disabled={!addJurorId}
                      >
                        <SelectTrigger className="flex-1 h-9 text-xs">
                          <SelectValue
                            placeholder={
                              addJurorId
                                ? 'Select project...'
                                : 'Select juror first'
                            }
                          />
                        </SelectTrigger>
                        <SelectContent>
                          {addJurorId &&
                            getAvailableProjectsForJuror(addJurorId).map((p) => (
                              <SelectItem key={p.id} value={p.id}>
                                <span className="truncate">{p.title}</span>
                                {p.category && (
                                  <span className="text-muted-foreground text-[10px] ml-1">
                                    ({p.category})
                                  </span>
                                )}
                              </SelectItem>
                            ))}
                        </SelectContent>
                      </Select>
                      <Button
                        size="sm"
                        className="h-9 shrink-0"
                        onClick={addAssignment}
                        disabled={!addJurorId || !addProjectId}
                      >
                        <Plus className="h-3.5 w-3.5 mr-1" />
                        Add
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </>
            ) : (
              <p className="text-sm text-muted-foreground">
                No preview data available
              </p>
            )}
          </div>
        </ScrollArea>

        <SheetFooter className="px-6 py-4 border-t shrink-0 gap-2 sm:gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleExecute}
            disabled={isExecuting || assignments.length === 0}
          >
            {isExecuting ? (
              <>
                <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
                Executing...
              </>
            ) : (
              <>
                <CheckCircle2 className="h-4 w-4 mr-1.5" />
                Execute {totalAssignments} Assignment{totalAssignments !== 1 ? 's' : ''}
              </>
            )}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}

// ─── Juror Group Card ────────────────────────────────────────────────────────

type JurorGroupProps = {
  group: {
    userId: string
    userName: string
    assignments: EditableAssignment[]
  }
  expanded: boolean
  onToggle: () => void
  onRemove: (localId: string) => void
  onAddProject: (projectId: string) => void
  availableProjects: Array<{ id: string; title: string; category?: string }>
  requiredReviews: number
}

function JurorGroup({
  group,
  expanded,
  onToggle,
  onRemove,
  onAddProject,
  availableProjects,
  requiredReviews,
}: JurorGroupProps) {
  const [inlineProjectId, setInlineProjectId] = useState('')

  const handleInlineAdd = () => {
    if (!inlineProjectId) return
    onAddProject(inlineProjectId)
    setInlineProjectId('')
  }

  const aiCount = group.assignments.filter((a) => !a.isManual).length
  const manualCount = group.assignments.filter((a) => a.isManual).length
  const avgScore =
    group.assignments.length > 0
      ? Math.round(
          group.assignments.reduce((sum, a) => sum + a.score, 0) /
            group.assignments.length,
        )
      : 0

  return (
    <Collapsible open={expanded} onOpenChange={onToggle}>
      <Card className="overflow-hidden">
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-muted/40 transition-colors"
          >
            {expanded ? (
              <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
            ) : (
              <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
            )}
            <div className="flex items-center gap-2 min-w-0 flex-1">
              <div className="h-7 w-7 rounded-full bg-brand-blue/10 flex items-center justify-center shrink-0">
                <User className="h-3.5 w-3.5 text-brand-blue" />
              </div>
              <span className="text-sm font-medium truncate">
                {group.userName}
              </span>
            </div>
            <div className="flex items-center gap-1.5 shrink-0">
              <Badge
                variant="secondary"
                className="text-[10px] tabular-nums h-5 px-1.5"
              >
                {group.assignments.length} project
                {group.assignments.length !== 1 ? 's' : ''}
              </Badge>
              {avgScore > 0 && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Badge
                        variant="outline"
                        className={cn(
                          'text-[10px] tabular-nums h-5 px-1.5',
                          avgScore >= 50
                            ? 'border-green-300 text-green-700'
                            : avgScore >= 25
                              ? 'border-amber-300 text-amber-700'
                              : 'border-red-300 text-red-700',
                        )}
                      >
                        {avgScore}
                      </Badge>
                    </TooltipTrigger>
                    <TooltipContent>Avg. match score</TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}
            </div>
          </button>
        </CollapsibleTrigger>

        <CollapsibleContent>
          <div className="border-t">
            {group.assignments.map((a) => (
              <AssignmentRow key={a.localId} assignment={a} onRemove={onRemove} />
            ))}

            {/* Inline add project */}
            {availableProjects.length > 0 && (
              <div className="flex items-center gap-2 px-3 py-2 bg-muted/20 border-t">
                <Select
                  value={inlineProjectId}
                  onValueChange={setInlineProjectId}
                >
                  <SelectTrigger className="flex-1 h-8 text-xs">
                    <SelectValue placeholder="Add project..." />
                  </SelectTrigger>
                  <SelectContent>
                    {availableProjects.map((p) => (
                      <SelectItem key={p.id} value={p.id}>
                        <span className="truncate">{p.title}</span>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-8 px-2 shrink-0"
                  onClick={handleInlineAdd}
                  disabled={!inlineProjectId}
                >
                  <Plus className="h-3.5 w-3.5" />
                </Button>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </Card>
    </Collapsible>
  )
}

// ─── Assignment Row ──────────────────────────────────────────────────────────

function AssignmentRow({
  assignment,
  onRemove,
}: {
  assignment: EditableAssignment
  onRemove: (localId: string) => void
}) {
  const a = assignment

  return (
    <div className="flex items-start gap-2 px-3 py-2 group hover:bg-muted/30 transition-colors border-t first:border-t-0">
      <div className="flex-1 min-w-0 space-y-1">
        <div className="flex items-center gap-1.5">
          <span className="text-sm font-medium truncate">{a.projectTitle}</span>
          {a.isManual ? (
            <Badge
              variant="outline"
              className="text-[10px] h-4 px-1 border-blue-300 text-blue-600 shrink-0"
            >
              Manual
            </Badge>
          ) : a.fromIntent ? (
            <Badge
              variant="outline"
              className="text-[10px] h-4 px-1 border-violet-300 text-violet-600 shrink-0"
            >
              Intent
            </Badge>
          ) : null}
        </div>

        {/* Score + tags + reasoning */}
        <div className="flex flex-wrap items-center gap-1">
          {!a.isManual && a.score > 0 && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Badge
                    variant="outline"
                    className={cn(
                      'text-[10px] h-4 px-1 tabular-nums',
                      a.score >= 50
                        ? 'border-green-300 text-green-700'
                        : a.score >= 25
                          ? 'border-amber-300 text-amber-700'
                          : 'border-red-300 text-red-700',
                    )}
                  >
                    <Sparkles className="h-2.5 w-2.5 mr-0.5" />
                    {Math.round(a.score)}
                  </Badge>
                </TooltipTrigger>
                <TooltipContent side="bottom" className="max-w-xs">
                  <p className="font-medium text-xs mb-1">Match Score Breakdown</p>
                  <ul className="text-xs space-y-0.5">
                    {a.reasoning.map((r, i) => (
                      <li key={i}>• {r}</li>
                    ))}
                  </ul>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
          {a.matchingTags.slice(0, 3).map((tag) => (
            <Badge
              key={tag}
              variant="secondary"
              className="text-[10px] h-4 px-1 gap-0.5"
            >
              <Tag className="h-2.5 w-2.5" />
              {tag}
            </Badge>
          ))}
          {a.matchingTags.length > 3 && (
            <span className="text-[10px] text-muted-foreground">
              +{a.matchingTags.length - 3} more
            </span>
          )}
        </div>

        {/* Policy violations */}
        {a.policyViolations.length > 0 && (
          <div className="flex items-center gap-1">
            <AlertTriangle className="h-3 w-3 text-amber-500 shrink-0" />
            <span className="text-[10px] text-amber-600 truncate">
              {a.policyViolations.join(', ')}
            </span>
          </div>
        )}
      </div>

      <Button
        variant="ghost"
        size="icon"
        className="h-7 w-7 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
        onClick={() => onRemove(a.localId)}
      >
        <X className="h-3.5 w-3.5" />
      </Button>
    </div>
  )
}
