'use client'

import { Fragment, useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { scoreGradient } from '@/components/charts/chart-theme'
import { ProjectPreviewDialog } from './project-preview-dialog'

interface JurorRow {
  userId: string
  name: string
  assigned: number
  completed: number
  completionRate: number
  averageScore: number
  stddev: number
  isOutlier: boolean
  projects: { id: string; title: string; evalStatus: string; score?: number | null }[]
}

interface ExpandableJurorTableProps {
  jurors: JurorRow[]
  roundId?: string
}

function evalStatusBadge(status: string) {
  switch (status) {
    case 'REVIEWED':
      return <Badge variant="default">Reviewed</Badge>
    case 'UNDER_REVIEW':
      return <Badge variant="secondary">Under Review</Badge>
    default:
      return <Badge variant="outline">Not Reviewed</Badge>
  }
}

function ScorePill({ score }: { score: number }) {
  const bg = scoreGradient(score)
  const text = score >= 6 ? '#ffffff' : '#1a1a1a'
  return (
    <span
      className="inline-flex items-center justify-center rounded-md px-2 py-0.5 text-xs font-semibold tabular-nums min-w-[36px]"
      style={{ backgroundColor: bg, color: text }}
    >
      {score.toFixed(1)}
    </span>
  )
}

export function ExpandableJurorTable({ jurors, roundId }: ExpandableJurorTableProps) {
  const [expanded, setExpanded] = useState<string | null>(null)
  const [previewProjectId, setPreviewProjectId] = useState<string | null>(null)

  function toggle(userId: string) {
    setExpanded((prev) => (prev === userId ? null : userId))
  }

  function openPreview(projectId: string, e: React.MouseEvent) {
    e.stopPropagation()
    setPreviewProjectId(projectId)
  }

  if (jurors.length === 0) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center py-12">
          <p className="text-sm text-muted-foreground">No juror data available</p>
        </CardContent>
      </Card>
    )
  }

  return (
    <>
      {/* Desktop table */}
      <div className="hidden md:block rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Juror</TableHead>
              <TableHead className="text-right tabular-nums">Assigned</TableHead>
              <TableHead className="text-right tabular-nums">Completed</TableHead>
              <TableHead>Rate</TableHead>
              <TableHead className="text-right tabular-nums">Avg Score</TableHead>
              <TableHead className="text-right tabular-nums">Std Dev</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="w-8" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {jurors.map((j) => (
              <Fragment key={j.userId}>
                <TableRow
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => toggle(j.userId)}
                >
                  <TableCell className="font-medium">{j.name}</TableCell>
                  <TableCell className="text-right tabular-nums">{j.assigned}</TableCell>
                  <TableCell className="text-right tabular-nums">{j.completed}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Progress value={j.completionRate} className="w-20 h-2" />
                      <span className="text-xs tabular-nums text-muted-foreground">
                        {j.completionRate.toFixed(0)}%
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="text-right tabular-nums">
                    {j.averageScore > 0 ? j.averageScore.toFixed(2) : '—'}
                  </TableCell>
                  <TableCell className="text-right tabular-nums">
                    {j.stddev > 0 ? j.stddev.toFixed(2) : '—'}
                  </TableCell>
                  <TableCell>
                    {j.isOutlier ? (
                      <Badge variant="destructive">Outlier</Badge>
                    ) : (
                      <Badge variant="outline">Normal</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    {expanded === j.userId ? (
                      <ChevronUp className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <ChevronDown className="h-4 w-4 text-muted-foreground" />
                    )}
                  </TableCell>
                </TableRow>
                {expanded === j.userId && (
                  <TableRow key={`${j.userId}-expanded`}>
                    <TableCell colSpan={8} className="bg-muted/30 p-0">
                      <div className="px-6 py-3">
                        {j.projects.length === 0 ? (
                          <p className="text-sm text-muted-foreground">No projects</p>
                        ) : (
                          <table className="w-full text-sm">
                            <thead>
                              <tr className="text-left text-xs text-muted-foreground border-b">
                                <th className="pb-2 font-medium">Project</th>
                                <th className="pb-2 font-medium text-center">Score</th>
                                <th className="pb-2 font-medium text-right">Status</th>
                              </tr>
                            </thead>
                            <tbody>
                              {j.projects.map((p) => (
                                <tr key={p.id} className="border-b last:border-0">
                                  <td className="py-2 pr-4">
                                    <button
                                      className="text-primary hover:underline text-left"
                                      onClick={(e) => openPreview(p.id, e)}
                                    >
                                      {p.title}
                                    </button>
                                  </td>
                                  <td className="py-2 text-center">
                                    {p.score != null ? (
                                      <ScorePill score={p.score} />
                                    ) : (
                                      <span className="text-xs text-muted-foreground">—</span>
                                    )}
                                  </td>
                                  <td className="py-2 text-right">{evalStatusBadge(p.evalStatus)}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </Fragment>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Mobile card stack */}
      <div className="space-y-3 md:hidden">
        {jurors.map((j) => (
          <Card key={j.userId}>
            <CardContent className="p-4">
              <button
                className="w-full text-left"
                onClick={() => toggle(j.userId)}
              >
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">{j.name}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {j.completed}/{j.assigned} completed
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    {j.isOutlier && <Badge variant="destructive">Outlier</Badge>}
                    {expanded === j.userId ? (
                      <ChevronUp className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <ChevronDown className="h-4 w-4 text-muted-foreground" />
                    )}
                  </div>
                </div>
                <div className="mt-2 flex items-center gap-2">
                  <Progress value={j.completionRate} className="flex-1 h-1.5" />
                  <span className="text-xs tabular-nums text-muted-foreground">
                    {j.completionRate.toFixed(0)}%
                  </span>
                </div>
                <div className="mt-2 grid grid-cols-2 gap-2 text-xs">
                  <div>
                    <span className="text-muted-foreground">Avg Score: </span>
                    <span className="tabular-nums font-medium">
                      {j.averageScore > 0 ? j.averageScore.toFixed(2) : '—'}
                    </span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Std Dev: </span>
                    <span className="tabular-nums font-medium">
                      {j.stddev > 0 ? j.stddev.toFixed(2) : '—'}
                    </span>
                  </div>
                </div>
              </button>

              {expanded === j.userId && j.projects.length > 0 && (
                <div className="mt-3 pt-3 border-t space-y-2">
                  {j.projects.map((p) => (
                    <div key={p.id} className="flex items-center justify-between gap-2">
                      <button
                        className="text-sm text-primary hover:underline truncate text-left"
                        onClick={(e) => openPreview(p.id, e)}
                      >
                        {p.title}
                      </button>
                      <div className="flex items-center gap-2 shrink-0">
                        {p.score != null && <ScorePill score={p.score} />}
                        {evalStatusBadge(p.evalStatus)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {expanded === j.userId && j.projects.length === 0 && (
                <p className="mt-3 pt-3 border-t text-sm text-muted-foreground">No projects</p>
              )}
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Project Preview Dialog */}
      <ProjectPreviewDialog
        projectId={previewProjectId}
        roundId={roundId}
        open={!!previewProjectId}
        onOpenChange={(open) => { if (!open) setPreviewProjectId(null) }}
      />
    </>
  )
}
