'use client'

import { useState, useEffect, useMemo, useRef } from 'react'
import {
  AlertTriangle,
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  Cpu,
  Loader2,
  Plus,
  Sparkles,
  Tag,
  User,
  X,
  Zap,
} 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 AssignmentMode = 'ai' | 'algorithm'

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 AIPreviewData = {
  assignments: any[]
  warnings: string[]
  stats: { totalProjects: number; totalJurors: number; assignmentsGenerated: number; unassignedProjects: number }
  fallbackUsed?: boolean
  tokensUsed?: number
}

type AssignmentPreviewSheetProps = {
  roundId: string
  open: boolean
  onOpenChange: (open: boolean) => void
  requiredReviews?: number
  /** AI preview result from parent (lifted mutation) */
  aiResult?: AIPreviewData | null
  /** Whether AI is currently generating */
  isAIGenerating?: boolean
  /** Trigger AI generation from parent */
  onGenerateAI?: () => void
  /** Reset AI results */
  onResetAI?: () => void
}

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

  const [mode, setMode] = useState<AssignmentMode>('ai')
  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>('')
  // Track staggered reveal for streaming effect
  const [visibleCount, setVisibleCount] = useState(0)
  const staggerTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  // ── Queries ──────────────────────────────────────────────────────────────

  // Algorithm mode query (only runs when algorithm mode is selected)
  const {
    data: algoPreview,
    isLoading: isAlgoLoading,
  } = trpc.roundAssignment.preview.useQuery(
    { roundId, honorIntents: true, requiredReviews },
    { enabled: open && mode === 'algorithm' },
  )

  // Active preview data based on mode
  const preview = mode === 'ai' ? aiResult : algoPreview
  const isLoading = mode === 'ai' ? isAIGenerating : isAlgoLoading

  // 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 with staggered reveal ──────────
  useEffect(() => {
    if (preview && !initialized) {
      const mapped: EditableAssignment[] = preview.assignments.map(
        (a: any, idx: number) => ({
          localId: `${mode}-${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)

      // Staggered reveal: show assignments one by one
      setVisibleCount(0)
      const totalGroups = new Set(mapped.map((a) => a.userId)).size
      let count = 0
      const reveal = () => {
        count++
        setVisibleCount(count)
        if (count < totalGroups) {
          staggerTimerRef.current = setTimeout(reveal, 150)
        }
      }
      // Start after a small delay for visual effect
      staggerTimerRef.current = setTimeout(reveal, 100)
    }
  }, [preview, initialized, mode])

  // Cleanup stagger timer
  useEffect(() => {
    return () => {
      if (staggerTimerRef.current) clearTimeout(staggerTimerRef.current)
    }
  }, [])

  // Reset when sheet closes (but preserve AI results in parent)
  useEffect(() => {
    if (!open) {
      setInitialized(false)
      setAssignments([])
      setExpandedJurors(new Set())
      setAddJurorId('')
      setAddProjectId('')
      setVisibleCount(0)
      if (staggerTimerRef.current) clearTimeout(staggerTimerRef.current)
    }
  }, [open])

  // Reset assignments when mode changes
  const handleModeChange = (newMode: AssignmentMode) => {
    if (newMode === mode) return
    setMode(newMode)
    setInitialized(false)
    setAssignments([])
    setExpandedJurors(new Set())
    setVisibleCount(0)
  }

  // ── 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 and make visible
    setExpandedJurors((prev) => new Set([...prev, addJurorId]))
    setVisibleCount((prev) => Math.max(prev, groupedByJuror.length + 1))
    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="text-sm">
            Review and fine-tune assignments before executing.
          </SheetDescription>

          {/* Mode toggle */}
          <div className="flex items-center gap-1 mt-2 p-1 rounded-lg bg-muted/50 w-fit">
            <button
              type="button"
              onClick={() => handleModeChange('ai')}
              className={cn(
                'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all',
                mode === 'ai'
                  ? 'bg-background shadow-sm text-foreground'
                  : 'text-muted-foreground hover:text-foreground',
              )}
            >
              <Sparkles className="h-3.5 w-3.5" />
              AI (GPT)
            </button>
            <button
              type="button"
              onClick={() => handleModeChange('algorithm')}
              className={cn(
                'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all',
                mode === 'algorithm'
                  ? 'bg-background shadow-sm text-foreground'
                  : 'text-muted-foreground hover:text-foreground',
              )}
            >
              <Cpu className="h-3.5 w-3.5" />
              Algorithm
            </button>
          </div>
        </SheetHeader>

        <ScrollArea className="flex-1 min-h-0">
          <div className="px-6 py-4 space-y-4">
            {/* AI mode: show generate button if no results yet */}
            {mode === 'ai' && !aiResult && !isAIGenerating && (
              <Card className="border-dashed">
                <CardContent className="flex flex-col items-center justify-center py-8 gap-3">
                  <div className="h-12 w-12 rounded-full bg-violet-100 flex items-center justify-center">
                    <Sparkles className="h-6 w-6 text-violet-600" />
                  </div>
                  <div className="text-center space-y-1">
                    <p className="font-medium text-sm">AI-Powered Assignments</p>
                    <p className="text-xs text-muted-foreground max-w-xs">
                      Uses GPT to analyze juror expertise, bios, project descriptions,
                      and documents to generate optimal assignments.
                    </p>
                  </div>
                  <Button
                    onClick={onGenerateAI}
                    className="gap-2 bg-violet-600 hover:bg-violet-700"
                    disabled={!onGenerateAI}
                  >
                    <Zap className="h-4 w-4" />
                    Generate with AI
                  </Button>
                </CardContent>
              </Card>
            )}

            {/* Loading state */}
            {isLoading ? (
              <div className="space-y-3">
                {mode === 'ai' && (
                  <Card className="border-violet-200 bg-violet-50/50">
                    <CardContent className="flex items-center gap-3 py-4">
                      <div className="relative">
                        <div className="h-6 w-6 rounded-full border-2 border-violet-300 border-t-violet-600 animate-spin" />
                      </div>
                      <div>
                        <p className="text-sm font-medium">Generating AI assignments...</p>
                        <p className="text-xs text-muted-foreground">
                          Analyzing juror expertise and project data with GPT
                        </p>
                      </div>
                    </CardContent>
                  </Card>
                )}
                {[1, 2, 3, 4].map((i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : preview ? (
              <>
                {/* AI metadata */}
                {mode === 'ai' && aiResult && (
                  <div className="flex flex-wrap items-center gap-2 text-xs">
                    <Badge variant="outline" className="gap-1 text-violet-600 border-violet-300">
                      <Sparkles className="h-3 w-3" />
                      AI Generated
                    </Badge>
                    {aiResult.fallbackUsed && (
                      <Badge variant="outline" className="gap-1 text-amber-600 border-amber-300">
                        <AlertTriangle className="h-3 w-3" />
                        Fallback algorithm used
                      </Badge>
                    )}
                    {(aiResult.tokensUsed ?? 0) > 0 && (
                      <span className="text-muted-foreground">
                        {aiResult.tokensUsed?.toLocaleString()} tokens used
                      </span>
                    )}
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-6 px-2 text-xs"
                      onClick={() => {
                        setInitialized(false)
                        setAssignments([])
                        setVisibleCount(0)
                        onGenerateAI?.()
                      }}
                    >
                      Regenerate
                    </Button>
                  </div>
                )}

                {mode === 'algorithm' && (
                  <div className="flex items-center gap-2 text-xs">
                    <Badge variant="outline" className="gap-1">
                      <Cpu className="h-3 w-3" />
                      Algorithm
                    </Badge>
                    <span className="text-muted-foreground">
                      Tag overlap + bio match + workload balancing
                    </span>
                  </div>
                )}

                {/* ── 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">
                    <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">
                              {w}
                            </p>
                          ))}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* ── Juror groups with staggered reveal ── */}
                <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, index) => (
                      <div
                        key={group.userId}
                        className={cn(
                          'transition-all duration-300',
                          index < visibleCount
                            ? 'opacity-100 translate-y-0'
                            : 'opacity-0 translate-y-2 pointer-events-none h-0 overflow-hidden',
                        )}
                      >
                        <JurorGroup
                          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>
                    ))
                  )}
                </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>
              </>
            ) : mode === 'algorithm' ? (
              <p className="text-sm text-muted-foreground">
                No preview data available
              </p>
            ) : null}
          </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,
}: JurorGroupProps) {
  const [inlineProjectId, setInlineProjectId] = useState('')

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

  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.5 group hover:bg-muted/30 transition-colors border-t first:border-t-0">
      <div className="flex-1 min-w-0 space-y-1.5">
        <div className="flex items-center gap-1.5">
          <span className="text-sm font-medium truncate">{a.projectTitle}</span>
          {!a.isManual && a.score > 0 && (
            <Badge
              variant="outline"
              className={cn(
                'text-[10px] h-4 px-1 tabular-nums shrink-0',
                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>
          )}
          {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>

        {/* AI reasoning — displayed directly */}
        {!a.isManual && a.reasoning.length > 0 && a.reasoning[0] !== 'Manually added by admin' && (
          <p className="text-xs text-muted-foreground leading-relaxed">
            {a.reasoning.join(' ')}
          </p>
        )}

        {/* Tags */}
        {a.matchingTags.length > 0 && (
          <div className="flex flex-wrap items-center gap-1">
            {a.matchingTags.slice(0, 4).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 > 4 && (
              <span className="text-[10px] text-muted-foreground">
                +{a.matchingTags.length - 4} 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>
  )
}
