'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import { StatusBadge } from '@/components/shared/status-badge'
import { AnimatedCard } from '@/components/shared/animated-container'
import {
  Target,
  TrendingUp,
  Users,
  ChevronDown,
  ChevronUp,
  Award,
} from 'lucide-react'
import { cn } from '@/lib/utils'

export function EvaluationPanel({ roundId, programId }: { roundId: string; programId: string }) {
  const [expandedJurorId, setExpandedJurorId] = useState<string | null>(null)

  const { data: roundStats, isLoading: statsLoading } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: advConfig } = trpc.analytics.getRoundAdvancementConfig.useQuery(
    { roundId },
    { refetchInterval: 60_000 },
  )

  const { data: dashStats } = trpc.analytics.getDashboardStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: jurorWorkload } = trpc.analytics.getJurorWorkload.useQuery(
    { programId, roundId },
    { enabled: !!programId, refetchInterval: 30_000 },
  )

  const { data: projectsData } = trpc.analytics.getAllProjects.useQuery(
    { roundId, perPage: 8 },
    { refetchInterval: 30_000 },
  )

  const stats = roundStats?.stats as {
    totalAssignments: number
    completedEvaluations: number
    completionRate: number
    activeJurors: number
  } | undefined

  const allJurors = jurorWorkload ?? []
  const projects = projectsData?.projects ?? []

  const scoreDistribution = dashStats?.scoreDistribution ?? []
  const maxScoreCount = Math.max(...scoreDistribution.map((b) => b.count), 1)
  const scoreColors: Record<string, string> = {
    '9-10': '#053d57',
    '7-8': '#1e7a8a',
    '5-6': '#557f8c',
    '3-4': '#c4453a',
    '1-2': '#de0f1e',
  }

  return (
    <div className="space-y-4">
      {/* Advancement Method Card */}
      {advConfig && (
        <AnimatedCard index={0}>
          <Card className="border-brand-teal/30 bg-brand-teal/5">
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="rounded-lg bg-brand-teal/10 p-2">
                  <Target className="h-5 w-5 text-brand-teal" />
                </div>
                <div>
                  <p className="text-sm font-semibold">
                    {advConfig.advanceMode === 'threshold'
                      ? `Score Threshold ≥ ${advConfig.advanceScoreThreshold ?? '?'}`
                      : 'Top N Advancement'}
                  </p>
                  {advConfig.advanceMode === 'count' && (
                    <p className="text-xs text-muted-foreground">
                      {advConfig.startupAdvanceCount != null && `${advConfig.startupAdvanceCount} Startups`}
                      {advConfig.startupAdvanceCount != null && advConfig.conceptAdvanceCount != null && ', '}
                      {advConfig.conceptAdvanceCount != null && `${advConfig.conceptAdvanceCount} Business Concepts`}
                    </p>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}

      {/* Completion Progress */}
      {statsLoading ? (
        <Skeleton className="h-20 rounded-lg" />
      ) : stats ? (
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium">Evaluation Progress</span>
            <Badge variant="secondary" className="tabular-nums">
              {stats.completionRate}%
            </Badge>
          </div>
          <Progress value={stats.completionRate} className="h-2 mb-1" />
          <p className="text-xs text-muted-foreground tabular-nums">
            {stats.completedEvaluations} / {stats.totalAssignments} evaluations · {stats.activeJurors} jurors
          </p>
        </Card>
      ) : null}

      {/* Score Distribution */}
      {scoreDistribution.length > 0 && (
        <AnimatedCard index={1}>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <TrendingUp className="h-4 w-4 text-amber-500" />
                Score Distribution
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1.5">
                {scoreDistribution.map((bucket) => (
                  <div key={bucket.label} className="flex items-center gap-2">
                    <span className="w-8 text-right text-[11px] font-medium tabular-nums text-muted-foreground">
                      {bucket.label}
                    </span>
                    <div className="flex-1 overflow-hidden rounded-full bg-muted" style={{ height: 14 }}>
                      <div
                        className="h-full rounded-full transition-all duration-500"
                        style={{
                          width: `${maxScoreCount > 0 ? (bucket.count / maxScoreCount) * 100 : 0}%`,
                          backgroundColor: scoreColors[bucket.label] ?? '#557f8c',
                        }}
                      />
                    </div>
                    <span className="w-6 text-right text-[11px] tabular-nums text-muted-foreground">
                      {bucket.count}
                    </span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}

      {/* Juror Workload */}
      <AnimatedCard index={2}>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="flex items-center gap-2 text-sm">
              <Users className="h-4 w-4 text-violet-500" />
              Juror Workload
            </CardTitle>
          </CardHeader>
          <CardContent>
            {allJurors.length > 0 ? (
              <div className="max-h-[320px] overflow-y-auto -mr-2 pr-2 space-y-2">
                {allJurors.map((juror) => {
                  const isExpanded = expandedJurorId === juror.id
                  return (
                    <div key={juror.id}>
                      <button
                        type="button"
                        className="w-full text-left space-y-1 rounded-md px-1 -mx-1 py-1 hover:bg-muted/50 transition-colors"
                        onClick={() => setExpandedJurorId(isExpanded ? null : juror.id)}
                      >
                        <div className="flex items-center justify-between text-sm">
                          <span className="truncate font-medium">{juror.name ?? 'Unknown'}</span>
                          <div className="ml-2 flex shrink-0 items-center gap-1.5">
                            <span className="text-xs tabular-nums text-muted-foreground">
                              {juror.completionRate}%
                            </span>
                            {isExpanded
                              ? <ChevronUp className="h-3 w-3 text-muted-foreground" />
                              : <ChevronDown className="h-3 w-3 text-muted-foreground" />}
                          </div>
                        </div>
                        <Progress value={juror.completionRate} className="h-1.5" />
                        <p className="text-[11px] text-muted-foreground">
                          {juror.completed} / {juror.assigned} evaluations
                        </p>
                      </button>
                      {isExpanded && juror.projects && (
                        <div className="ml-1 mt-1 space-y-1 border-l-2 border-muted pl-3">
                          {juror.projects.map((proj: { id: string; title: string; evalStatus: string }) => (
                            <Link
                              key={proj.id}
                              href={`/observer/projects/${proj.id}` as Route}
                              className="flex items-center justify-between gap-2 rounded py-1 text-xs hover:underline"
                            >
                              <span className="truncate">{proj.title}</span>
                              <StatusBadge status={proj.evalStatus} size="sm" />
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">No juror assignments yet.</p>
            )}
          </CardContent>
        </Card>
      </AnimatedCard>

      {/* Recently Reviewed */}
      {projects.length > 0 && (
        <AnimatedCard index={3}>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <Award className="h-4 w-4 text-emerald-500" />
                Recently Reviewed
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <div className="divide-y">
                {projects
                  .filter((p) => {
                    const s = p.observerStatus ?? p.status
                    return s !== 'PENDING'
                  })
                  .slice(0, 6)
                  .map((p) => (
                    <Link
                      key={p.id}
                      href={`/observer/projects/${p.id}` as Route}
                      className="flex items-center justify-between gap-2 px-4 py-2.5 hover:bg-muted/50 transition-colors"
                    >
                      <span className="text-sm truncate">{p.title}</span>
                      <div className="flex items-center gap-2 shrink-0">
                        <StatusBadge status={p.observerStatus ?? p.status} size="sm" />
                        <span className="text-xs tabular-nums text-muted-foreground">
                          {p.evaluationCount > 0 && p.averageScore !== null
                            ? p.averageScore.toFixed(1)
                            : '—'}
                        </span>
                      </div>
                    </Link>
                  ))}
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      )}
    </div>
  )
}
