'use client'

import { useState, useCallback } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import {
  FileSpreadsheet,
  BarChart3,
  Users,
  TrendingUp,
  Download,
  Clock,
  ClipboardCheck,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import {
  ScoreDistributionChart,
  EvaluationTimelineChart,
  StatusBreakdownChart,
  CriteriaScoresChart,
  JurorConsistencyChart,
  JurorScoreHeatmap,
} from '@/components/charts'
import { BarChart } from '@tremor/react'
import { CsvExportDialog } from '@/components/shared/csv-export-dialog'
import { ExportPdfButton } from '@/components/shared/export-pdf-button'
import { AnimatedCard } from '@/components/shared/animated-container'
import { ExpandableJurorTable } from './expandable-juror-table'

const ROUND_TYPE_LABELS: Record<string, string> = {
  INTAKE: 'Intake',
  FILTERING: 'Filtering',
  EVALUATION: 'Evaluation',
  SUBMISSION: 'Submission',
  MENTORING: 'Mentoring',
  LIVE_FINAL: 'Live Final',
  DELIBERATION: 'Deliberation',
}

type Stage = {
  id: string
  name: string
  status: string
  roundType: string
  windowCloseAt: Date | null
  _count: { projects: number; assignments: number; evaluations: number }
  programId: string
  programName: string
}

function roundStatusLabel(status: string): string {
  if (status === 'ROUND_ACTIVE') return 'Active'
  if (status === 'ROUND_CLOSED') return 'Closed'
  if (status === 'ROUND_DRAFT') return 'Draft'
  if (status === 'ROUND_ARCHIVED') return 'Archived'
  return status
}

function roundStatusVariant(status: string): 'default' | 'secondary' | 'outline' {
  if (status === 'ROUND_ACTIVE') return 'default'
  if (status === 'ROUND_CLOSED') return 'secondary'
  return 'outline'
}

function parseSelection(value: string | null): { roundId?: string; programId?: string } {
  if (!value) return {}
  if (value.startsWith('all:')) return { programId: value.slice(4) }
  return { roundId: value }
}

interface EvaluationReportTabsProps {
  roundId: string
  programId: string
  stages: Stage[]
  selectedValue: string | null
}

// ---- Progress sub-tab ----

function ProgressSubTab({
  selectedValue,
  stages,
  stagesLoading,
  selectedRound,
}: {
  selectedValue: string | null
  stages: Stage[]
  stagesLoading: boolean
  selectedRound: Stage | undefined
}) {
  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

  const { data: overviewStats, isLoading: statsLoading } =
    trpc.analytics.getOverviewStats.useQuery(queryInput, { enabled: hasSelection })

  const { data: timeline, isLoading: timelineLoading } =
    trpc.analytics.getEvaluationTimeline.useQuery(queryInput, { enabled: hasSelection })

  const [csvOpen, setCsvOpen] = useState(false)
  const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
  const [csvLoading, setCsvLoading] = useState(false)

  const handleRequestCsvData = useCallback(async () => {
    setCsvLoading(true)
    const columns = ['roundName', 'roundType', 'status', 'projects', 'assignments', 'completionRate']
    const data = stages.map((s) => {
      const assigned = s._count.assignments
      const projects = s._count.projects
      const rate = assigned > 0 && projects > 0 ? Math.round((assigned / projects) * 100) : 0
      return {
        roundName: s.name,
        roundType: ROUND_TYPE_LABELS[s.roundType] || s.roundType,
        status: roundStatusLabel(s.status),
        projects,
        assignments: assigned,
        completionRate: rate,
      }
    })
    const result = { data, columns }
    setCsvData(result)
    setCsvLoading(false)
    return result
  }, [stages])

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-end flex-wrap gap-3">
        <div className="flex items-center gap-2">
          {selectedValue && !selectedValue.startsWith('all:') && (
            <ExportPdfButton
              roundId={selectedValue}
              roundName={selectedRound?.name}
              programName={selectedRound?.programName}
            />
          )}
          <Button
            variant="outline"
            size="sm"
            onClick={() => setCsvOpen(true)}
            disabled={stagesLoading || stages.length === 0}
          >
            <Download className="mr-2 h-4 w-4" />
            Export CSV
          </Button>
        </div>
      </div>

      <CsvExportDialog
        open={csvOpen}
        onOpenChange={setCsvOpen}
        exportData={csvData}
        isLoading={csvLoading}
        filename="round-progress"
        onRequestData={handleRequestCsvData}
      />

      {/* Stats tiles */}
      {hasSelection && (
        <>
          {statsLoading ? (
            <div className="grid gap-4 sm:grid-cols-3">
              {[...Array(3)].map((_, i) => (
                <Card key={i}>
                  <CardHeader className="space-y-0 pb-2">
                    <Skeleton className="h-4 w-20" />
                  </CardHeader>
                  <CardContent>
                    <Skeleton className="h-8 w-16" />
                    <Skeleton className="mt-2 h-3 w-24" />
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : overviewStats ? (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <AnimatedCard index={0}>
                <Card className="border-l-4 border-l-blue-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardContent className="p-5">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Projects</p>
                        <p className="text-2xl font-bold mt-1">{overviewStats.projectCount}</p>
                        <p className="text-xs text-muted-foreground mt-1">In round</p>
                      </div>
                      <div className="rounded-xl bg-blue-50 p-3">
                        <FileSpreadsheet className="h-5 w-5 text-blue-600" />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </AnimatedCard>

              <AnimatedCard index={1}>
                <Card className="border-l-4 border-l-teal-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardContent className="p-5">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Juror Assignments</p>
                        <p className="text-2xl font-bold mt-1">{overviewStats.assignmentCount}</p>
                        <p className="text-xs text-muted-foreground mt-1">
                          {overviewStats.projectCount > 0
                            ? `${(overviewStats.assignmentCount / overviewStats.projectCount).toFixed(1)} reviews/project`
                            : 'No projects'}
                        </p>
                      </div>
                      <div className="rounded-xl bg-teal-50 p-3">
                        <ClipboardCheck className="h-5 w-5 text-teal-600" />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </AnimatedCard>

              <AnimatedCard index={2}>
                <Card className="border-l-4 border-l-emerald-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardContent className="p-5">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-muted-foreground">Evaluations</p>
                        <p className="text-2xl font-bold mt-1">{overviewStats.evaluationCount}</p>
                        <p className="text-xs text-muted-foreground mt-1">
                          {overviewStats.assignmentCount > 0
                            ? `${overviewStats.evaluationCount}/${overviewStats.assignmentCount} submitted`
                            : 'Submitted'}
                        </p>
                      </div>
                      <div className="rounded-xl bg-emerald-50 p-3">
                        <TrendingUp className="h-5 w-5 text-emerald-600" />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </AnimatedCard>

              <AnimatedCard index={3}>
                <Card className="border-l-4 border-l-violet-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardContent className="p-5">
                    <div>
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-sm font-medium text-muted-foreground">Completion</p>
                          <p className="text-2xl font-bold mt-1">{overviewStats.completionRate}%</p>
                        </div>
                        <div className="rounded-xl bg-violet-50 p-3">
                          <BarChart3 className="h-5 w-5 text-violet-600" />
                        </div>
                      </div>
                      <Progress value={overviewStats.completionRate} className="mt-3 h-2" gradient />
                    </div>
                  </CardContent>
                </Card>
              </AnimatedCard>
            </div>
          ) : null}
        </>
      )}

      {/* Completion Timeline */}
      {hasSelection && (
        <>
          {timelineLoading ? (
            <Skeleton className="h-[320px]" />
          ) : timeline?.length ? (
            <EvaluationTimelineChart data={timeline} />
          ) : (
            <Card>
              <CardContent className="flex items-center justify-center py-12">
                <p className="text-muted-foreground text-sm">No evaluation timeline data available yet</p>
              </CardContent>
            </Card>
          )}
        </>
      )}

      {/* Round Breakdown Table - Desktop */}
      {stagesLoading ? (
        <Skeleton className="h-[300px]" />
      ) : (
        <>
          <Card className="hidden md:block">
            <CardHeader>
              <CardTitle>Round Breakdown</CardTitle>
              <CardDescription>Progress overview for each round</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Round</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Projects</TableHead>
                    <TableHead className="text-right">Juror Assignments</TableHead>
                    <TableHead className="min-w-[140px]">Completion</TableHead>
                    <TableHead className="text-right">Avg Days</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stages.map((stage) => {
                    const projects = stage._count.projects
                    const assignments = stage._count.assignments
                    const evaluations = stage._count.evaluations
                    const isClosed = stage.status === 'ROUND_CLOSED' || stage.status === 'ROUND_ARCHIVED'
                    const rate = isClosed
                      ? 100
                      : assignments > 0
                        ? Math.min(100, Math.round((evaluations / assignments) * 100))
                        : 0
                    return (
                      <TableRow key={stage.id}>
                        <TableCell>
                          <div>
                            <p className="font-medium">{stage.name}</p>
                            {stage.windowCloseAt && (
                              <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                                <Clock className="h-3 w-3" />
                                {formatDateOnly(stage.windowCloseAt)}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">
                            {ROUND_TYPE_LABELS[stage.roundType] || stage.roundType}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant={roundStatusVariant(stage.status)}>
                            {roundStatusLabel(stage.status)}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">{projects}</TableCell>
                        <TableCell className="text-right">{assignments}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Progress value={rate} className="h-2 w-20" />
                            <span className="text-sm tabular-nums">{rate}%</span>
                          </div>
                        </TableCell>
                        <TableCell className="text-right text-muted-foreground">-</TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          {/* Round Breakdown Cards - Mobile */}
          <div className="space-y-3 md:hidden">
            <h2 className="text-base font-semibold">Round Breakdown</h2>
            {stages.map((stage) => {
              const projects = stage._count.projects
              const assignments = stage._count.assignments
              const evaluations = stage._count.evaluations
              const isClosed = stage.status === 'ROUND_CLOSED' || stage.status === 'ROUND_ARCHIVED'
              const rate = isClosed
                ? 100
                : assignments > 0
                  ? Math.min(100, Math.round((evaluations / assignments) * 100))
                  : 0
              return (
                <Card key={stage.id}>
                  <CardContent className="pt-4 space-y-3">
                    <div className="flex items-start justify-between gap-2">
                      <p className="font-medium leading-tight">{stage.name}</p>
                      <Badge variant={roundStatusVariant(stage.status)} className="shrink-0">
                        {roundStatusLabel(stage.status)}
                      </Badge>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">
                        {ROUND_TYPE_LABELS[stage.roundType] || stage.roundType}
                      </Badge>
                    </div>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      <div>
                        <p className="text-muted-foreground text-xs">Projects</p>
                        <p className="font-medium">{projects}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground text-xs">Juror Assignments</p>
                        <p className="font-medium">{assignments}</p>
                      </div>
                    </div>
                    <div>
                      <div className="flex items-center justify-between text-sm mb-1">
                        <span className="text-muted-foreground text-xs">Completion</span>
                        <span className="font-medium">{rate}%</span>
                      </div>
                      <Progress value={rate} className="h-2" />
                    </div>
                    {stage.windowCloseAt && (
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <Clock className="h-3 w-3" />
                        Closes: {formatDateOnly(stage.windowCloseAt)}
                      </p>
                    )}
                  </CardContent>
                </Card>
              )
            })}
          </div>
        </>
      )}
    </div>
  )
}

// ---- Jurors sub-tab ----

function JurorsSubTab({ roundId, selectedValue }: { roundId: string; selectedValue: string | null }) {
  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

  const { data: workload, isLoading: workloadLoading } =
    trpc.analytics.getJurorWorkload.useQuery(queryInput, { enabled: hasSelection })

  const { data: consistency, isLoading: consistencyLoading } =
    trpc.analytics.getJurorConsistency.useQuery(queryInput, { enabled: hasSelection })

  const { data: heatmapData, isLoading: heatmapLoading } =
    trpc.analytics.getJurorScoreMatrix.useQuery({ roundId }, { enabled: !!roundId })

  const [csvOpen, setCsvOpen] = useState(false)
  const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
  const [csvLoading, setCsvLoading] = useState(false)

  type WorkloadItem = { id: string; name: string; assigned: number; completed: number; completionRate: number; projects: { id: string; title: string; evalStatus: string }[] }
  type ConsistencyJuror = { userId: string; name: string; evaluationCount: number; averageScore: number; stddev: number; isOutlier: boolean }

  const handleRequestCsvData = useCallback(async () => {
    setCsvLoading(true)
    const columns = ['name', 'assigned', 'completed', 'completionRate', 'avgScore', 'stddev', 'isOutlier']

    const workloadMap = new Map<string, WorkloadItem>()
    if (workload) {
      for (const w of (workload as unknown as WorkloadItem[])) {
        workloadMap.set(w.id, w)
      }
    }

    const jurors = (consistency as { overallAverage: number; jurors: ConsistencyJuror[] } | undefined)?.jurors ?? []
    const data = jurors.map((j) => {
      const w = workloadMap.get(j.userId)
      return {
        name: j.name,
        assigned: w?.assigned ?? '-',
        completed: w?.completed ?? '-',
        completionRate: w ? `${w.completionRate}%` : '-',
        avgScore: j.averageScore,
        stddev: j.stddev,
        isOutlier: j.isOutlier ? 'Yes' : 'No',
      }
    })

    const result = { data, columns }
    setCsvData(result)
    setCsvLoading(false)
    return result
  }, [workload, consistency])

  const isLoading = workloadLoading || consistencyLoading

  type JurorRow = {
    userId: string
    name: string
    assigned: number
    completed: number
    completionRate: number
    averageScore: number
    stddev: number
    isOutlier: boolean
    projects: { id: string; title: string; evalStatus: string }[]
  }

  const jurors: JurorRow[] = (() => {
    if (!consistency) return []
    const workloadMap = new Map<string, WorkloadItem>()
    if (workload) {
      for (const w of (workload as unknown as WorkloadItem[])) {
        workloadMap.set(w.id, w)
      }
    }
    const jurorList = (consistency as { overallAverage: number; jurors: ConsistencyJuror[] }).jurors ?? []
    return jurorList
      .map((j) => {
        const w = workloadMap.get(j.userId)
        return {
          userId: j.userId,
          name: j.name,
          assigned: w?.assigned ?? 0,
          completed: w?.completed ?? 0,
          completionRate: w?.completionRate ?? 0,
          averageScore: j.averageScore,
          stddev: j.stddev,
          isOutlier: j.isOutlier,
          projects: w?.projects ?? [],
        }
      })
      .sort((a, b) => b.assigned - a.assigned)
  })()

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-base font-semibold">Juror Performance</h2>
          <p className="text-sm text-muted-foreground">Workload and scoring consistency per juror</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setCsvOpen(true)}
          disabled={!hasSelection || isLoading}
        >
          <Download className="mr-2 h-4 w-4" />
          Export CSV
        </Button>
      </div>

      <CsvExportDialog
        open={csvOpen}
        onOpenChange={setCsvOpen}
        exportData={csvData}
        isLoading={csvLoading}
        filename="juror-performance"
        onRequestData={handleRequestCsvData}
      />

      {/* Expandable Juror Table */}
      {isLoading ? (
        <Skeleton className="h-[400px]" />
      ) : jurors.length > 0 ? (
        <ExpandableJurorTable jurors={jurors} roundId={roundId} />
      ) : hasSelection ? (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <p className="text-sm text-muted-foreground">No juror data available for this selection</p>
          </CardContent>
        </Card>
      ) : null}

      {/* Juror Score Heatmap */}
      {heatmapLoading ? (
        <Skeleton className="h-[400px]" />
      ) : heatmapData ? (
        <JurorScoreHeatmap
          jurors={heatmapData.jurors}
          projects={heatmapData.projects}
          cells={heatmapData.cells}
          truncated={heatmapData.truncated}
          totalProjects={heatmapData.totalProjects}
        />
      ) : null}

      {/* Juror Consistency Chart */}
      {consistencyLoading ? (
        <Skeleton className="h-[400px]" />
      ) : consistency ? (
        <JurorConsistencyChart
          data={consistency as { overallAverage: number; jurors: Array<{ userId: string; name: string; evaluationCount: number; averageScore: number; stddev: number; deviationFromOverall: number; isOutlier: boolean }> }}
        />
      ) : null}
    </div>
  )
}

// ---- Scores sub-tab ----

function ScoresSubTab({ selectedValue, programId }: { selectedValue: string | null; programId: string }) {
  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

  const { data: scoreDistribution, isLoading: scoreLoading } =
    trpc.analytics.getScoreDistribution.useQuery(queryInput, { enabled: hasSelection })

  const { data: statusBreakdown, isLoading: statusLoading } =
    trpc.analytics.getStatusBreakdown.useQuery(queryInput, { enabled: hasSelection })

  const { data: criteriaScores, isLoading: criteriaLoading } =
    trpc.analytics.getCriteriaScores.useQuery(queryInput, { enabled: hasSelection })

  const geoProgramId = queryInput.programId || programId
  const { data: geoData, isLoading: geoLoading } =
    trpc.analytics.getGeographicDistribution.useQuery(
      { programId: geoProgramId, roundId: queryInput.roundId },
      { enabled: !!geoProgramId }
    )

  const [csvOpen, setCsvOpen] = useState(false)
  const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
  const [csvLoading, setCsvLoading] = useState(false)

  type CriterionItem = { criterionName: string; averageScore: number; count: number }

  const handleRequestCsvData = useCallback(async () => {
    setCsvLoading(true)
    const columns = ['criterionName', 'averageScore', 'count']
    const data = ((criteriaScores as CriterionItem[] | undefined) ?? []).map((c) => ({
      criterionName: c.criterionName,
      averageScore: c.averageScore,
      count: c.count,
    }))
    const result = { data, columns }
    setCsvData(result)
    setCsvLoading(false)
    return result
  }, [criteriaScores])

  const countryChartData = (() => {
    if (!geoData?.length) return []
    const sorted = [...geoData].sort((a, b) => b.count - a.count)
    return sorted.slice(0, 15).map((d) => {
      let name = d.countryCode
      try {
        const displayNames = new Intl.DisplayNames(['en'], { type: 'region' })
        name = displayNames.of(d.countryCode.toUpperCase()) || d.countryCode
      } catch { /* keep code */ }
      return { country: name, Projects: d.count }
    })
  })()

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-base font-semibold">Scores & Analytics</h2>
          <p className="text-sm text-muted-foreground">Score distributions, criteria breakdown and geographic data</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setCsvOpen(true)}
          disabled={!hasSelection || criteriaLoading}
        >
          <Download className="mr-2 h-4 w-4" />
          Export CSV
        </Button>
      </div>

      <CsvExportDialog
        open={csvOpen}
        onOpenChange={setCsvOpen}
        exportData={csvData}
        isLoading={csvLoading}
        filename="scores-criteria"
        onRequestData={handleRequestCsvData}
      />

      {/* Score Distribution & Status Breakdown */}
      <div className="grid gap-6 lg:grid-cols-2">
        {scoreLoading ? (
          <Skeleton className="h-[350px]" />
        ) : scoreDistribution ? (
          <ScoreDistributionChart
            data={scoreDistribution.distribution ?? []}
            averageScore={scoreDistribution.averageScore ?? 0}
            totalScores={scoreDistribution.totalScores ?? 0}
          />
        ) : hasSelection ? (
          <Card>
            <CardContent className="flex items-center justify-center py-12">
              <p className="text-sm text-muted-foreground">No score data available yet</p>
            </CardContent>
          </Card>
        ) : null}

        {statusLoading ? (
          <Skeleton className="h-[350px]" />
        ) : statusBreakdown ? (
          <StatusBreakdownChart data={statusBreakdown} />
        ) : hasSelection ? (
          <Card>
            <CardContent className="flex items-center justify-center py-12">
              <p className="text-sm text-muted-foreground">No status data available yet</p>
            </CardContent>
          </Card>
        ) : null}
      </div>

      {/* Criteria Breakdown */}
      {criteriaLoading ? (
        <Skeleton className="h-[350px]" />
      ) : criteriaScores?.length ? (
        <CriteriaScoresChart data={criteriaScores} />
      ) : hasSelection ? (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <p className="text-sm text-muted-foreground">No criteria score data available yet</p>
          </CardContent>
        </Card>
      ) : null}

      {/* Country Distribution */}
      {geoLoading ? (
        <Skeleton className="h-[400px]" />
      ) : countryChartData.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>Top Countries</span>
              <span className="text-sm font-normal text-muted-foreground">
                {geoData?.length ?? 0} countries represented
              </span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <BarChart
              data={countryChartData}
              index="country"
              categories={['Projects']}
              colors={['blue']}
              layout="vertical"
              yAxisWidth={140}
              showLegend={false}
              className="h-[400px]"
            />
          </CardContent>
        </Card>
      ) : null}
    </div>
  )
}

// ---- Main component ----

export function EvaluationReportTabs({ roundId, programId, stages, selectedValue }: EvaluationReportTabsProps) {
  const selectedRound = stages.find((s) => s.id === selectedValue)
  const stagesLoading = false // stages passed from parent already loaded

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-base font-semibold">Evaluation Overview</h2>
        <p className="text-sm text-muted-foreground">Evaluation progress and juror performance</p>
      </div>
    <Tabs defaultValue="progress" className="space-y-6">
      <TabsList>
        <TabsTrigger value="progress" className="gap-2">
          <TrendingUp className="h-4 w-4" />
          Progress
        </TabsTrigger>
        <TabsTrigger value="jurors" className="gap-2">
          <Users className="h-4 w-4" />
          Jurors
        </TabsTrigger>
        <TabsTrigger value="scores" className="gap-2">
          <BarChart3 className="h-4 w-4" />
          Scores
        </TabsTrigger>
      </TabsList>

      <TabsContent value="progress">
        <ProgressSubTab
          selectedValue={selectedValue}
          stages={stages}
          stagesLoading={stagesLoading}
          selectedRound={selectedRound}
        />
      </TabsContent>

      <TabsContent value="jurors">
        <JurorsSubTab roundId={roundId} selectedValue={selectedValue} />
      </TabsContent>

      <TabsContent value="scores">
        <ScoresSubTab selectedValue={selectedValue} programId={programId} />
      </TabsContent>
    </Tabs>
    </div>
  )
}
