'use client'

import { trpc } from '@/lib/trpc/client'
import { Card, CardContent } from '@/components/ui/card'
import { AnimatedCard } from '@/components/shared/animated-container'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Inbox,
  Filter,
  ClipboardCheck,
  Upload,
  Users,
  Presentation,
  Vote,
  CheckCircle2,
  BarChart3,
  FileText,
  MessageSquare,
  Lock,
  Globe,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'

interface StatCardData {
  label: string
  value: string | number
  icon: LucideIcon
  color: string
}

function StatCard({ label, value, icon: Icon, color, index }: StatCardData & { index: number }) {
  return (
    <AnimatedCard index={index}>
      <Card className="relative overflow-hidden">
        <div className={`absolute left-0 top-0 bottom-0 w-1`} style={{ backgroundColor: color }} />
        <CardContent className="flex items-center gap-4 pt-6">
          <div className="rounded-lg p-2" style={{ backgroundColor: `${color}15` }}>
            <Icon className="h-5 w-5" style={{ color }} />
          </div>
          <div>
            <p className="text-2xl font-bold tabular-nums">{value}</p>
            <p className="text-sm text-muted-foreground">{label}</p>
          </div>
        </CardContent>
      </Card>
    </AnimatedCard>
  )
}

interface RoundTypeStatsCardsProps {
  roundId: string
}

export function RoundTypeStatsCards({ roundId }: RoundTypeStatsCardsProps) {
  const { data, isLoading } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { enabled: !!roundId }
  )

  if (isLoading) {
    return (
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, i) => (
          <Card key={i}>
            <CardContent className="pt-6">
              <Skeleton className="h-8 w-16" />
              <Skeleton className="mt-2 h-4 w-24" />
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  if (!data) return null

  const stats = data.stats as Record<string, unknown>

  const cards: StatCardData[] = (() => {
    switch (data.roundType) {
      case 'INTAKE':
        return [
          { label: 'Total Projects', value: (stats.totalProjects as number) ?? 0, icon: Inbox, color: '#053d57' },
          { label: 'Start-ups', value: (stats.startupCount as number) ?? 0, icon: BarChart3, color: '#1e7a8a' },
          { label: 'Business Concepts', value: (stats.conceptCount as number) ?? 0, icon: FileText, color: '#557f8c' },
          { label: 'Countries', value: (stats.countryCount as number) ?? 0, icon: Globe, color: '#2d8659' },
        ]

      case 'FILTERING':
        return [
          { label: 'Total Screened', value: (stats.totalScreened as number) ?? 0, icon: Filter, color: '#053d57' },
          { label: 'Passed', value: (stats.passed as number) ?? 0, icon: CheckCircle2, color: '#2d8659' },
          { label: 'Filtered Out', value: (stats.filteredOut as number) ?? 0, icon: Filter, color: '#de0f1e' },
          { label: 'Pass Rate', value: `${(stats.passRate as number) ?? 0}%`, icon: BarChart3, color: '#557f8c' },
        ]

      case 'EVALUATION':
        return [
          { label: 'Assignments', value: (stats.totalAssignments as number) ?? 0, icon: ClipboardCheck, color: '#053d57' },
          { label: 'Completed', value: (stats.completedEvaluations as number) ?? 0, icon: CheckCircle2, color: '#2d8659' },
          { label: 'Completion Rate', value: `${(stats.completionRate as number) ?? 0}%`, icon: BarChart3, color: '#557f8c' },
          { label: 'Active Jurors', value: (stats.activeJurors as number) ?? 0, icon: Users, color: '#1e7a8a' },
        ]

      case 'SUBMISSION':
        return [
          { label: 'Total Files', value: (stats.totalFiles as number) ?? 0, icon: Upload, color: '#053d57' },
          { label: 'Teams with Uploads', value: (stats.teamsSubmitted as number) ?? 0, icon: FileText, color: '#557f8c' },
        ]

      case 'MENTORING':
        return [
          { label: 'Mentor Assignments', value: (stats.mentorAssignments as number) ?? 0, icon: Users, color: '#053d57' },
          { label: 'Total Messages', value: (stats.totalMessages as number) ?? 0, icon: MessageSquare, color: '#557f8c' },
        ]

      case 'LIVE_FINAL':
        return [
          { label: 'Session Status', value: formatSessionStatus((stats.sessionStatus as string) ?? 'NOT_STARTED'), icon: Presentation, color: '#053d57' },
          { label: 'Total Votes', value: (stats.voteCount as number) ?? 0, icon: Vote, color: '#de0f1e' },
        ]

      case 'DELIBERATION':
        return [
          { label: 'Sessions', value: (stats.totalSessions as number) ?? 0, icon: Users, color: '#053d57' },
          { label: 'Votes Cast', value: (stats.totalVotes as number) ?? 0, icon: Vote, color: '#557f8c' },
          { label: 'Results Locked', value: (stats.resultsLocked as number) ?? 0, icon: Lock, color: '#2d8659' },
        ]

      default:
        return []
    }
  })()

  if (cards.length === 0) return null

  return (
    <div className={
      cards.length <= 2
        ? 'grid gap-4 sm:grid-cols-2'
        : cards.length === 3
          ? 'grid gap-4 sm:grid-cols-2 lg:grid-cols-3'
          : 'grid gap-4 sm:grid-cols-2 lg:grid-cols-4'
    }>
      {cards.map((card, i) => (
        <StatCard key={card.label} {...card} index={i} />
      ))}
    </div>
  )
}

function formatSessionStatus(status: string): string {
  switch (status) {
    case 'NOT_STARTED': return 'Not Started'
    case 'IN_PROGRESS': return 'In Progress'
    case 'PAUSED': return 'Paused'
    case 'COMPLETED': return 'Completed'
    default: return status
  }
}
