'use client'

import { useState } from 'react'
import Link from 'next/link'
import { motion } from 'motion/react'
import {
  Clock,
  ArrowRight,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { StatusBadge } from '@/components/shared/status-badge'
import { cn, formatEnumLabel, daysUntil } from '@/lib/utils'
import { roundTypeConfig, projectStateConfig } from '@/lib/round-config'
import { trpc } from '@/lib/trpc/client'

export type PipelineRound = {
  id: string
  name: string
  roundType: string
  status: string
  projectStates: {
    PENDING: number
    IN_PROGRESS: number
    PASSED: number
    REJECTED: number
    COMPLETED: number
    WITHDRAWN: number
    total: number
  }
  assignmentCount: number
  evalSubmitted: number
  evalDraft: number
  evalTotal: number
  filteringPassed: number
  filteringRejected: number
  filteringFlagged: number
  filteringTotal: number
  liveSessionStatus: string | null
  deliberationCount: number
  windowOpenAt: Date | null
  windowCloseAt: Date | null
  sortOrder: number
  slug: string
}

type ActiveRoundPanelProps = {
  round: PipelineRound
}

const roundTypeIcons: Record<string, React.ElementType> = Object.fromEntries(
  Object.entries(roundTypeConfig).map(([k, v]) => [k, v.icon])
)

const stateColors: Record<string, { bg: string; label: string }> = Object.fromEntries(
  Object.entries(projectStateConfig).map(([k, v]) => [k, { bg: v.bg, label: v.label }])
)

function DeadlineCountdown({ date }: { date: Date }) {
  const days = daysUntil(date)

  if (days < 0) {
    return (
      <Badge variant="secondary" className="gap-1">
        <Clock className="h-3 w-3" />
        Closed
      </Badge>
    )
  }

  return (
    <Badge
      variant={days <= 2 ? 'destructive' : days <= 7 ? 'warning' : 'info'}
      className="gap-1"
    >
      <Clock className="h-3 w-3" />
      {days === 0 ? 'Closes today' : `${days}d left`}
    </Badge>
  )
}

function ProjectStateBar({
  projectStates,
}: {
  projectStates: PipelineRound['projectStates']
}) {
  const total = projectStates.total
  if (total === 0) return null

  const segments = (
    ['PENDING', 'IN_PROGRESS', 'PASSED', 'REJECTED', 'COMPLETED', 'WITHDRAWN'] as const
  ).filter((key) => projectStates[key] > 0)

  return (
    <TooltipProvider>
      <div className="space-y-2">
        <div className="flex h-3 w-full overflow-hidden rounded-full bg-muted">
          {segments.map((key) => {
            const pct = (projectStates[key] / total) * 100
            const color = stateColors[key]

            return (
              <Tooltip key={key}>
                <TooltipTrigger asChild>
                  <motion.div
                    className={cn('h-full', color.bg)}
                    initial={{ width: 0 }}
                    animate={{ width: `${pct}%` }}
                    transition={{ duration: 0.6, ease: 'easeOut' }}
                  />
                </TooltipTrigger>
                <TooltipContent>
                  {color.label}: {projectStates[key]} ({Math.round(pct)}%)
                </TooltipContent>
              </Tooltip>
            )
          })}
        </div>
        <div className="flex flex-wrap gap-x-4 gap-y-1">
          {segments.map((key) => {
            const color = stateColors[key]
            return (
              <div key={key} className="flex items-center gap-1.5 text-xs text-muted-foreground">
                <span className={cn('inline-block h-2 w-2 rounded-full', color.bg)} />
                {color.label}: {projectStates[key]}
              </div>
            )
          })}
        </div>
      </div>
    </TooltipProvider>
  )
}

function EvaluationRoundContent({ round }: { round: PipelineRound }) {
  const [showAll, setShowAll] = useState(false)

  const { data: workload, isLoading: isLoadingWorkload } = trpc.analytics.getJurorWorkload.useQuery(
    { roundId: round.id },
    { enabled: round.roundType === 'EVALUATION' }
  )

  const pct =
    round.evalTotal > 0
      ? Math.round((round.evalSubmitted / round.evalTotal) * 100)
      : 0

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between text-sm">
        <span className="text-muted-foreground">Evaluation progress</span>
        <span className="font-medium">
          {round.evalSubmitted} / {round.evalTotal} ({pct}%)
        </span>
      </div>
      <Progress value={pct} gradient />
      {round.evalDraft > 0 && (
        <p className="text-xs text-amber-600">
          {round.evalDraft} draft{round.evalDraft !== 1 ? 's' : ''} in progress
        </p>
      )}
      {/* Per-juror progress */}
      <div className="mt-3 space-y-1.5">
        <div className="flex items-center justify-between">
          <span className="text-xs font-medium text-muted-foreground">Jury Progress</span>
          {workload && workload.length > 8 && (
            <button
              onClick={() => setShowAll(!showAll)}
              className="text-xs text-primary hover:underline"
            >
              {showAll ? 'Show less' : `Show all (${workload.length})`}
            </button>
          )}
        </div>
        {isLoadingWorkload ? (
          <div className="space-y-1">
            {Array.from({ length: 3 }).map((_, i) => (
              <Skeleton key={i} className="h-4 w-full" />
            ))}
          </div>
        ) : workload && workload.length > 0 ? (
          <div className="space-y-1">
            {(showAll ? workload : workload.slice(0, 8)).map((juror) => {
              const pct = juror.assigned > 0 ? (juror.completed / juror.assigned) * 100 : 0
              return (
                <div key={juror.id} className="flex items-center gap-2">
                  <span className="max-w-[140px] truncate text-xs">{juror.name}</span>
                  <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
                    <div
                      className="h-full rounded-full bg-primary transition-all"
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                  <span className="whitespace-nowrap text-xs text-muted-foreground">
                    {juror.completed}/{juror.assigned}
                  </span>
                </div>
              )
            })}
          </div>
        ) : (
          <p className="text-xs text-muted-foreground">No jurors assigned yet</p>
        )}
      </div>
    </div>
  )
}

function RoundTypeContent({ round }: { round: PipelineRound }) {
  const { projectStates } = round

  switch (round.roundType) {
    case 'INTAKE':
      return (
        <p className="text-sm text-muted-foreground">
          Projects are submitting documents. {projectStates.PASSED} auto-passed,{' '}
          {projectStates.PENDING} pending.
        </p>
      )

    case 'FILTERING': {
      const processed = round.filteringPassed + round.filteringRejected + round.filteringFlagged
      const total = round.projectStates.total || round.filteringTotal
      const pct = total > 0 ? Math.round((processed / total) * 100) : 0

      return (
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">Filtering progress</span>
            <span className="font-medium">{pct}%</span>
          </div>
          <Progress value={pct} gradient />
          <div className="flex gap-4 text-xs text-muted-foreground">
            <span className="text-emerald-600">{round.filteringPassed} passed</span>
            <span className="text-red-600">{round.filteringRejected} failed</span>
            <span className="text-amber-600">{round.filteringFlagged} flagged</span>
          </div>
        </div>
      )
    }

    case 'EVALUATION':
      return <EvaluationRoundContent round={round} />

    case 'SUBMISSION':
      return (
        <p className="text-sm text-muted-foreground">
          {projectStates.COMPLETED} submissions completed, {projectStates.IN_PROGRESS} in
          progress, {projectStates.PENDING} pending.
        </p>
      )

    case 'MENTORING':
      return (
        <p className="text-sm text-muted-foreground">
          Mentoring phase active. {round.assignmentCount} mentor assignment
          {round.assignmentCount !== 1 ? 's' : ''} configured.{' '}
          {projectStates.COMPLETED} projects completed mentoring.
        </p>
      )

    case 'LIVE_FINAL':
      return (
        <div className="space-y-1">
          <p className="text-sm text-muted-foreground">
            Live finals round.{' '}
            {round.liveSessionStatus
              ? `Session: ${formatEnumLabel(round.liveSessionStatus)}`
              : 'No session started yet.'}
          </p>
          <p className="text-xs text-muted-foreground">
            {projectStates.total} projects in round, {projectStates.COMPLETED} completed.
          </p>
        </div>
      )

    case 'DELIBERATION':
      return (
        <p className="text-sm text-muted-foreground">
          Deliberation phase.{' '}
          {round.deliberationCount > 0
            ? `${round.deliberationCount} deliberation session${round.deliberationCount !== 1 ? 's' : ''} recorded.`
            : 'No deliberation sessions yet.'}
        </p>
      )

    default:
      return (
        <p className="text-sm text-muted-foreground">
          {projectStates.total} projects in this round.
        </p>
      )
  }
}

export function ActiveRoundPanel({ round }: ActiveRoundPanelProps) {
  const Icon = roundTypeIcons[round.roundType] || roundTypeConfig.INTAKE.icon

  return (
    <Card>
      <CardHeader className="flex flex-row items-center gap-3 space-y-0 pb-4">
        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-blue/10">
          <Icon className="h-5 w-5 text-brand-blue" />
        </div>
        <div className="min-w-0 flex-1">
          <CardTitle className="truncate">{round.name}</CardTitle>
          <p className="mt-0.5 text-xs text-muted-foreground">
            {formatEnumLabel(round.roundType)}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <StatusBadge status={round.status} size="sm" />
          {round.windowCloseAt && (
            <DeadlineCountdown date={new Date(round.windowCloseAt)} />
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <ProjectStateBar projectStates={round.projectStates} />
        <RoundTypeContent round={round} />
        <div className="pt-1">
          <Button asChild size="sm">
            <Link href={`/admin/rounds/${round.id}`}>
              Manage Round
              <ArrowRight className="h-4 w-4" />
            </Link>
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
