'use client'

import { Fragment, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { scoreGradient } from './chart-theme'

interface JurorScoreHeatmapProps {
  jurors: { id: string; name: string }[]
  projects: { id: string; title: string }[]
  cells: { jurorId: string; projectId: string; score: number | null }[]
  truncated?: boolean
  totalProjects?: number
}

function getScoreColor(score: number | null): string {
  if (score === null) return 'transparent'
  return scoreGradient(score)
}

function getTextColor(score: number | null): string {
  if (score === null) return 'inherit'
  return '#ffffff'
}

function ScoreBadge({ score }: { score: number }) {
  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: getScoreColor(score),
        color: getTextColor(score),
      }}
    >
      {score.toFixed(1)}
    </span>
  )
}

function JurorSummaryRow({
  juror,
  scores,
  averageScore,
  projectCount,
  isExpanded,
  onToggle,
  projects,
}: {
  juror: { id: string; name: string }
  scores: { projectId: string; score: number | null }[]
  averageScore: number | null
  projectCount: number
  isExpanded: boolean
  onToggle: () => void
  projects: { id: string; title: string }[]
}) {
  const scored = scores.filter((s) => s.score !== null)
  const unscored = projectCount - scored.length

  return (
    <>
      <tr
        className="border-b cursor-pointer transition-colors hover:bg-muted/50"
        onClick={onToggle}
      >
        <td className="py-3 px-4 font-medium text-sm whitespace-nowrap">
          <div className="flex items-center gap-2">
            <span className={`inline-flex h-5 w-5 items-center justify-center rounded text-[10px] font-bold transition-transform ${isExpanded ? 'rotate-90' : ''}`}>
              ›
            </span>
            {juror.name}
          </div>
        </td>
        <td className="py-3 px-4 text-center tabular-nums text-sm">
          {scored.length}
        </td>
        <td className="py-3 px-4 text-center">
          {averageScore !== null ? (
            <ScoreBadge score={averageScore} />
          ) : (
            <span className="text-xs text-muted-foreground">—</span>
          )}
        </td>
        <td className="py-3 px-4">
          {/* Mini score bar */}
          <div className="flex items-center gap-0.5">
            {scored
              .sort((a, b) => (a.score ?? 0) - (b.score ?? 0))
              .map((s, i) => (
                <div
                  key={i}
                  className="h-4 w-1.5 rounded-full"
                  style={{ backgroundColor: getScoreColor(s.score) }}
                  title={`${s.score?.toFixed(1)}`}
                />
              ))}
            {unscored > 0 &&
              Array.from({ length: Math.min(unscored, 10) }).map((_, i) => (
                <div
                  key={`empty-${i}`}
                  className="h-4 w-1.5 rounded-full bg-muted"
                />
              ))}
          </div>
        </td>
      </tr>
      {isExpanded && (
        <tr className="border-b bg-muted/30">
          <td colSpan={4} className="p-4">
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
              {projects.map((p) => {
                const cell = scores.find((s) => s.projectId === p.id)
                const score = cell?.score ?? null
                return (
                  <div
                    key={p.id}
                    className="flex items-center gap-2 rounded-md border bg-background px-2.5 py-1.5"
                  >
                    {score !== null ? (
                      <ScoreBadge score={score} />
                    ) : (
                      <span className="inline-flex items-center justify-center rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground min-w-[36px]">
                        —
                      </span>
                    )}
                    <span className="text-xs truncate" title={p.title}>
                      {p.title}
                    </span>
                  </div>
                )
              })}
            </div>
          </td>
        </tr>
      )}
    </>
  )
}

export function JurorScoreHeatmap({
  jurors,
  projects,
  cells,
  truncated,
  totalProjects,
}: JurorScoreHeatmapProps) {
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const cellMap = new Map<string, number | null>()
  for (const c of cells) {
    cellMap.set(`${c.jurorId}:${c.projectId}`, c.score)
  }

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

  // Compute per-juror data
  const jurorData = jurors.map((j) => {
    const scores = projects.map((p) => ({
      projectId: p.id,
      score: cellMap.get(`${j.id}:${p.id}`) ?? null,
    }))
    const scored = scores.filter((s) => s.score !== null)
    const avg = scored.length > 0
      ? scored.reduce((sum, s) => sum + (s.score ?? 0), 0) / scored.length
      : null
    return { juror: j, scores, averageScore: avg ? parseFloat(avg.toFixed(1)) : null, scoredCount: scored.length }
  })

  // Sort: jurors with most evaluations first
  jurorData.sort((a, b) => b.scoredCount - a.scoredCount)

  // Color legend
  const legendScores = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  return (
    <Card>
      <CardHeader>
        <div className="flex items-start justify-between gap-4">
          <div>
            <CardTitle className="text-base">Score Heatmap</CardTitle>
            <CardDescription>
              {jurors.length} juror{jurors.length !== 1 ? 's' : ''} &middot; {projects.length} project{projects.length !== 1 ? 's' : ''}
              {truncated && totalProjects ? ` (top ${projects.length} of ${totalProjects})` : ''}
            </CardDescription>
          </div>
          {/* Color legend */}
          <div className="hidden sm:flex items-center gap-1 shrink-0">
            <span className="text-[10px] text-muted-foreground mr-1">Low</span>
            {legendScores.map((s) => (
              <div
                key={s}
                className="h-4 w-4 rounded-sm"
                style={{ backgroundColor: getScoreColor(s) }}
                title={s.toString()}
              />
            ))}
            <span className="text-[10px] text-muted-foreground ml-1">High</span>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b text-xs text-muted-foreground">
                <th className="text-left py-2 px-4 font-medium">Juror</th>
                <th className="text-center py-2 px-4 font-medium whitespace-nowrap">Reviewed</th>
                <th className="text-center py-2 px-4 font-medium">Avg</th>
                <th className="text-left py-2 px-4 font-medium">Score Distribution</th>
              </tr>
            </thead>
            <tbody>
              {jurorData.map(({ juror, scores, averageScore }) => (
                <JurorSummaryRow
                  key={juror.id}
                  juror={juror}
                  scores={scores}
                  averageScore={averageScore}
                  projectCount={projects.length}
                  isExpanded={expandedId === juror.id}
                  onToggle={() => setExpandedId(expandedId === juror.id ? null : juror.id)}
                  projects={projects}
                />
              ))}
            </tbody>
          </table>
        </div>
      </CardContent>
    </Card>
  )
}
