'use client'

import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { AnimatedCard } from '@/components/shared/animated-container'
import { Star, MessageSquare, Trophy, Vote, ShieldCheck } from 'lucide-react'
import { cn } from '@/lib/utils'

type Criterion = {
  id?: string
  type?: string
  label?: string
  name?: string
  scale?: string
  maxScore?: number
}

type Evaluation = {
  id: string
  submittedAt: Date | null
  globalScore: number | null
  criterionScores: unknown
  feedbackText: string | null
  criteria: unknown
}

type EvaluationRound = {
  roundId: string
  roundName: string
  roundType: string
  evaluationCount: number
  evaluations: Evaluation[]
}

const HIDDEN_CRITERION_TYPES = new Set(['boolean', 'advance'])

function parseScaleMax(scale: string | undefined, fallback = 10): number {
  if (!scale) return fallback
  const m = scale.match(/^\s*\d+\s*-\s*(\d+)\s*$/)
  if (m) return Number(m[1])
  return fallback
}

function getCriterionMax(c: Criterion): number {
  if (typeof c.maxScore === 'number' && c.maxScore > 0) return c.maxScore
  return parseScaleMax(c.scale)
}

function visibleCriteria(criteria: unknown): Criterion[] {
  if (!Array.isArray(criteria)) return []
  return (criteria as Criterion[]).filter((c) => {
    if (!c) return false
    if (!c.id && !c.label && !c.name) return false
    if (c.type && HIDDEN_CRITERION_TYPES.has(c.type)) return false
    return true
  })
}

function globalScoreSummary(round: EvaluationRound) {
  if (round.roundType === 'DELIBERATION') return null
  const scores = round.evaluations
    .map((ev) => ev.globalScore)
    .filter((s): s is number => s !== null)
  if (scores.length === 0) return null
  const max = 10
  const avg = scores.reduce((a, b) => a + b, 0) / scores.length
  const lowest = Math.min(...scores)
  const highest = Math.max(...scores)
  return { avg, lowest, highest, max }
}

function RoundIcon({ roundType, className }: { roundType: string; className?: string }) {
  if (roundType === 'LIVE_FINAL') return <Trophy className={cn('h-4 w-4 text-amber-500', className)} />
  if (roundType === 'DELIBERATION') return <Vote className={cn('h-4 w-4 text-violet-500', className)} />
  return <Star className={cn('h-4 w-4 text-yellow-500', className)} />
}

function roundIconBg(roundType: string) {
  if (roundType === 'LIVE_FINAL') return 'bg-amber-500/10'
  if (roundType === 'DELIBERATION') return 'bg-violet-500/10'
  return 'bg-yellow-500/10'
}

function CriterionBar({ value, max }: { value: number; max: number }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100))
  return (
    <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
      <div
        className="h-full rounded-full bg-brand-blue transition-all"
        style={{ width: `${pct}%` }}
      />
    </div>
  )
}

function NumericCriterion({ label, score, max }: { label: string; score: number | undefined; max: number }) {
  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-sm">
        <span className="text-muted-foreground">{label}</span>
        <span className="font-semibold tabular-nums">
          {score !== undefined ? score : '—'}
          <span className="text-muted-foreground font-normal text-xs"> / {max}</span>
        </span>
      </div>
      {score !== undefined && <CriterionBar value={score} max={max} />}
    </div>
  )
}

function TextCriterion({ label, value }: { label: string; value: string }) {
  return (
    <div className="space-y-1.5">
      <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
        {label}
      </div>
      <div className="rounded-lg bg-muted/40 px-4 py-3 border-l-3 border-brand-teal">
        <p className="text-sm italic text-muted-foreground leading-relaxed whitespace-pre-wrap">
          {value}
        </p>
      </div>
    </div>
  )
}

export default function ApplicantEvaluationsPage() {
  const { data: rounds, isLoading } = trpc.applicant.getMyEvaluations.useQuery()

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold">Jury Feedback</h1>
          <p className="text-muted-foreground">Anonymous evaluations from jury members</p>
        </div>
        <div className="space-y-4">
          {[1, 2].map((i) => (
            <Card key={i}>
              <CardContent className="py-6">
                <Skeleton className="h-6 w-48 mb-4" />
                <Skeleton className="h-24 w-full" />
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  const hasEvaluations = rounds && rounds.length > 0

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Jury Feedback</h1>
        <p className="text-muted-foreground">
          {hasEvaluations
            ? `Anonymous evaluations from jury members across ${rounds.length} round${rounds.length === 1 ? '' : 's'}.`
            : 'Anonymous evaluations from jury members.'}
        </p>
      </div>

      {!hasEvaluations ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <div className="rounded-2xl bg-muted/60 p-4 mb-4">
              <Star className="h-8 w-8 text-muted-foreground/50" />
            </div>
            <h3 className="text-lg font-medium mb-2">No Evaluations Available</h3>
            <p className="text-muted-foreground text-center max-w-md">
              Evaluations will appear here once jury review is complete and results are published.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-6">
          {rounds.map((round, roundIdx) => {
            const summary = globalScoreSummary(round)

            return (
              <AnimatedCard key={round.roundId} index={roundIdx}>
                <Card>
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between gap-3">
                      <CardTitle className="flex items-center gap-2.5">
                        <div className={cn('rounded-lg p-1.5', roundIconBg(round.roundType))}>
                          <RoundIcon roundType={round.roundType} />
                        </div>
                        <div>
                          <span>{round.roundName}</span>
                          {summary && (
                            <p className="text-sm font-normal text-muted-foreground mt-0.5">
                              Average <span className="font-semibold text-foreground">{summary.avg.toFixed(1)}</span> / {summary.max}
                              {summary.lowest !== summary.highest && (
                                <span className="ml-2">· Lowest {summary.lowest} · Highest {summary.highest}</span>
                              )}
                            </p>
                          )}
                        </div>
                      </CardTitle>
                      <Badge variant="secondary" className="shrink-0">
                        {round.evaluationCount} {round.roundType === 'DELIBERATION' ? 'vote' : 'review'}{round.evaluationCount !== 1 ? 's' : ''}
                      </Badge>
                    </div>
                  </CardHeader>

                  <CardContent className="p-0">
                    <div className="divide-y">
                      {round.evaluations.map((ev, idx) => {
                        const criteria = visibleCriteria(ev.criteria)
                        const scores = (ev.criterionScores ?? {}) as Record<string, unknown>

                        return (
                          <div key={ev.id} className="px-6 py-4 space-y-4">
                            <div className="flex items-center justify-between">
                              <span className="font-medium text-sm">
                                {round.roundType === 'DELIBERATION' ? `Juror #${idx + 1}` : `Evaluator #${idx + 1}`}
                              </span>
                              <div className="flex items-center gap-3">
                                {ev.globalScore !== null && round.roundType !== 'DELIBERATION' && (
                                  <span className="flex items-center gap-1">
                                    <Star className="h-3.5 w-3.5 text-yellow-500" />
                                    <span className="text-sm font-bold tabular-nums">{ev.globalScore}</span>
                                    <span className="text-xs text-muted-foreground">/ 10</span>
                                  </span>
                                )}
                                {ev.submittedAt && (
                                  <span className="text-xs text-muted-foreground">
                                    {new Date(ev.submittedAt).toLocaleDateString()}
                                  </span>
                                )}
                              </div>
                            </div>

                            {criteria.length > 0 && (
                              <div className="space-y-3">
                                {criteria.map((c, ci) => {
                                  const key = c.id || String(ci)
                                  const label = c.label || c.name || `Criterion ${ci + 1}`
                                  const raw = scores[key]

                                  if (c.type === 'text') {
                                    if (typeof raw !== 'string' || raw.trim() === '') return null
                                    return <TextCriterion key={key} label={label} value={raw} />
                                  }

                                  // numeric (default)
                                  const score = typeof raw === 'number' ? raw : undefined
                                  const max = getCriterionMax(c)
                                  return <NumericCriterion key={key} label={label} score={score} max={max} />
                                })}
                              </div>
                            )}

                            {ev.feedbackText && (
                              <div className="space-y-1.5">
                                <div className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                                  <MessageSquare className="h-3.5 w-3.5" />
                                  {round.roundType === 'DELIBERATION' ? 'Result' : 'Written Feedback'}
                                </div>
                                <div className="rounded-lg bg-muted/40 px-4 py-3 border-l-3 border-brand-teal">
                                  <p className="text-sm italic text-muted-foreground leading-relaxed whitespace-pre-wrap">
                                    {ev.feedbackText}
                                  </p>
                                </div>
                              </div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  </CardContent>
                </Card>
              </AnimatedCard>
            )
          })}

          <div className="flex items-center justify-center gap-2 py-2">
            <ShieldCheck className="h-4 w-4 text-muted-foreground/60" />
            <p className="text-xs text-muted-foreground">
              Evaluator identities are kept confidential.
            </p>
          </div>
        </div>
      )}
    </div>
  )
}
