'use client'

import { useState } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  FileSpreadsheet,
  BarChart3,
  Users,
  ClipboardList,
  CheckCircle2,
  TrendingUp,
  GitCompare,
  UserCheck,
  Globe,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import {
  ScoreDistributionChart,
  EvaluationTimelineChart,
  StatusBreakdownChart,
  JurorWorkloadChart,
  ProjectRankingsChart,
  CriteriaScoresChart,
  CrossRoundComparisonChart,
  JurorConsistencyChart,
  DiversityMetricsChart,
} from '@/components/charts'
import { ExportPdfButton } from '@/components/shared/export-pdf-button'
import { AnimatedCard } from '@/components/shared/animated-container'

// Parse selection value: "all:programId" for edition-wide, or roundId
function parseSelection(value: string | null): { roundId?: string; programId?: string } {
  if (!value) return {}
  if (value.startsWith('all:')) return { programId: value.slice(4) }
  return { roundId: value }
}

function OverviewTab({ selectedValue }: { selectedValue: string | null }) {
  const { data: programs, isLoading } = trpc.program.list.useQuery({ includeRounds: true })

  const rounds = programs?.flatMap(p =>
    p.rounds.map(r => ({
      ...r,
      programName: `${p.year} Edition`,
    }))
  ) || []

  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

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

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].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>
      </div>
    )
  }

  const totalProjects = rounds.reduce((acc, r) => acc + (r._count?.projects || 0), 0)
  const activeRounds = rounds.filter((r) => r.status === 'ACTIVE').length
  const totalPrograms = programs?.length || 0

  return (
    <div className="space-y-6">
      {/* Quick Stats */}
      <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">Total Rounds</p>
                  <p className="text-2xl font-bold mt-1">{rounds.length}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {activeRounds} active
                  </p>
                </div>
                <div className="rounded-xl bg-blue-50 p-3">
                  <BarChart3 className="h-5 w-5 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>

        <AnimatedCard index={1}>
          <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">Total Projects</p>
                  <p className="text-2xl font-bold mt-1">{totalProjects}</p>
                  <p className="text-xs text-muted-foreground mt-1">Across all rounds</p>
                </div>
                <div className="rounded-xl bg-emerald-50 p-3">
                  <ClipboardList className="h-5 w-5 text-emerald-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>

        <AnimatedCard index={2}>
          <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 className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Active Rounds</p>
                  <p className="text-2xl font-bold mt-1">{activeRounds}</p>
                  <p className="text-xs text-muted-foreground mt-1">Currently active</p>
                </div>
                <div className="rounded-xl bg-violet-50 p-3">
                  <Users className="h-5 w-5 text-violet-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>

        <AnimatedCard index={3}>
          <Card className="border-l-4 border-l-brand-teal 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">Programs</p>
                  <p className="text-2xl font-bold mt-1">{totalPrograms}</p>
                  <p className="text-xs text-muted-foreground mt-1">Total programs</p>
                </div>
                <div className="rounded-xl bg-brand-teal/10 p-3">
                  <CheckCircle2 className="h-5 w-5 text-brand-teal" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      </div>

      {/* Round/edition-specific overview stats */}
      {hasSelection && (
        <>
          {statsLoading ? (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {[...Array(4)].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="space-y-4">
              <h3 className="text-lg font-semibold">{queryInput.programId ? 'Edition Overview' : 'Selected Round Details'}</h3>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Projects</CardTitle>
                    <ClipboardList className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{overviewStats.projectCount}</div>
                    <p className="text-xs text-muted-foreground">In this round</p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Assignments</CardTitle>
                    <Users className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{overviewStats.assignmentCount}</div>
                    <p className="text-xs text-muted-foreground">
                      {overviewStats.jurorCount} jurors
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Evaluations</CardTitle>
                    <FileSpreadsheet className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{overviewStats.evaluationCount}</div>
                    <p className="text-xs text-muted-foreground">Submitted</p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Completion</CardTitle>
                    <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{overviewStats.completionRate}%</div>
                    <Progress value={overviewStats.completionRate} className="mt-2 h-2" gradient />
                  </CardContent>
                </Card>
              </div>
            </div>
          ) : null}
        </>
      )}

      {/* Rounds Table - Desktop */}
      <Card className="hidden md:block">
        <CardHeader>
          <CardTitle>Round Reports</CardTitle>
          <CardDescription>Progress overview for each round</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Round</TableHead>
                <TableHead>Program</TableHead>
                <TableHead>Projects</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rounds.map((round) => (
                <TableRow key={round.id}>
                  <TableCell>
                    <div>
                      <p className="font-medium">{round.name}</p>
                      {round.votingEndAt && (
                        <p className="text-sm text-muted-foreground">
                          Ends: {formatDateOnly(round.votingEndAt)}
                        </p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>{round.programName}</TableCell>
                  <TableCell>{round._count?.projects || '-'}</TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        round.status === 'ACTIVE'
                          ? 'default'
                          : round.status === 'CLOSED'
                            ? 'secondary'
                            : 'outline'
                      }
                    >
                      {round.status}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Rounds Cards - Mobile */}
      <div className="space-y-4 md:hidden">
        <h2 className="text-lg font-semibold">Round Reports</h2>
        {rounds.map((round) => (
          <Card key={round.id}>
            <CardContent className="pt-4 space-y-3">
              <div className="flex items-center justify-between">
                <p className="font-medium">{round.name}</p>
                <Badge
                  variant={
                    round.status === 'ACTIVE'
                      ? 'default'
                      : round.status === 'CLOSED'
                        ? 'secondary'
                        : 'outline'
                  }
                >
                  {round.status}
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">{round.programName}</p>
              {round.votingEndAt && (
                <p className="text-xs text-muted-foreground">
                  Ends: {formatDateOnly(round.votingEndAt)}
                </p>
              )}
              <div className="text-sm">
                <span>{round._count?.projects || 0} projects</span>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}

function AnalyticsTab({ selectedValue }: { selectedValue: 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: timeline, isLoading: timelineLoading } =
    trpc.analytics.getEvaluationTimeline.useQuery(
      queryInput,
      { enabled: hasSelection }
    )

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

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

  const { data: projectRankings, isLoading: rankingsLoading } =
    trpc.analytics.getProjectRankings.useQuery(
      { ...queryInput, limit: 15 },
      { enabled: hasSelection }
    )

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

  return (
    <div className="space-y-6">
      {/* Row 1: 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}
            totalScores={scoreDistribution.totalScores}
          />
        ) : null}

        {statusLoading ? (
          <Skeleton className="h-[350px]" />
        ) : statusBreakdown ? (
          <StatusBreakdownChart data={statusBreakdown} />
        ) : null}
      </div>

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

      {/* Row 3: Criteria Scores */}
      {criteriaLoading ? (
        <Skeleton className="h-[350px]" />
      ) : criteriaScores?.length ? (
        <CriteriaScoresChart data={criteriaScores} />
      ) : null}

      {/* Row 4: Juror Workload */}
      {workloadLoading ? (
        <Skeleton className="h-[450px]" />
      ) : jurorWorkload?.length ? (
        <JurorWorkloadChart data={jurorWorkload} />
      ) : (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <p className="text-muted-foreground">
              No juror assignments yet
            </p>
          </CardContent>
        </Card>
      )}

      {/* Row 5: Project Rankings */}
      {rankingsLoading ? (
        <Skeleton className="h-[550px]" />
      ) : projectRankings?.length ? (
        <ProjectRankingsChart data={projectRankings} limit={15} />
      ) : (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <p className="text-muted-foreground">
              No project scores available yet
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

function CrossRoundTab() {
  const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })

  const rounds = programs?.flatMap(p =>
    p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
  ) || []

  const [selectedRoundIds, setSelectedRoundIds] = useState<string[]>([])

  const { data: comparison, isLoading: comparisonLoading } =
    trpc.analytics.getCrossRoundComparison.useQuery(
      { roundIds: selectedRoundIds },
      { enabled: selectedRoundIds.length >= 2 }
    )

  const toggleRound = (roundId: string) => {
    setSelectedRoundIds((prev) =>
      prev.includes(roundId)
        ? prev.filter((id) => id !== roundId)
        : [...prev, roundId]
    )
  }

  if (programsLoading) return <Skeleton className="h-[400px]" />

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Select Rounds to Compare</CardTitle>
          <CardDescription>Choose at least 2 rounds</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {rounds.map((round) => (
              <Badge
                key={round.id}
                variant={selectedRoundIds.includes(round.id) ? 'default' : 'outline'}
                className="cursor-pointer text-sm py-1.5 px-3"
                onClick={() => toggleRound(round.id)}
              >
                {round.programName} - {round.name}
              </Badge>
            ))}
          </div>
          {selectedRoundIds.length < 2 && (
            <p className="text-sm text-muted-foreground mt-3">
              Select at least 2 rounds to enable comparison
            </p>
          )}
        </CardContent>
      </Card>

      {comparisonLoading && selectedRoundIds.length >= 2 && <Skeleton className="h-[350px]" />}

      {comparison && (
        <CrossRoundComparisonChart data={comparison as Array<{
          roundId: string; roundName: string; projectCount: number; evaluationCount: number
          completionRate: number; averageScore: number | null
          scoreDistribution: { score: number; count: number }[]
        }>} />
      )}
    </div>
  )
}

function JurorConsistencyTab({ selectedValue }: { selectedValue: string }) {
  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

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

  if (isLoading) return <Skeleton className="h-[400px]" />

  if (!consistency) return null

  return (
    <JurorConsistencyChart
      data={consistency as {
        overallAverage: number
        jurors: Array<{
          userId: string; name: string; email: string
          evaluationCount: number; averageScore: number
          stddev: number; deviationFromOverall: number; isOutlier: boolean
        }>
      }}
    />
  )
}

function DiversityTab({ selectedValue }: { selectedValue: string }) {
  const queryInput = parseSelection(selectedValue)
  const hasSelection = !!queryInput.roundId || !!queryInput.programId

  const { data: diversity, isLoading } =
    trpc.analytics.getDiversityMetrics.useQuery(
      queryInput,
      { enabled: hasSelection }
    )

  if (isLoading) return <Skeleton className="h-[400px]" />

  if (!diversity) return null

  return (
    <DiversityMetricsChart
      data={diversity as {
        total: number
        byCountry: { country: string; count: number; percentage: number }[]
        byCategory: { category: string; count: number; percentage: number }[]
        byOceanIssue: { issue: string; count: number; percentage: number }[]
        byTag: { tag: string; count: number; percentage: number }[]
      }}
    />
  )
}

export default function ObserverReportsPage() {
  const [selectedValue, setSelectedValue] = useState<string | null>(null)

  const { data: programs, isLoading: roundsLoading } = trpc.program.list.useQuery({ includeRounds: true })

  const rounds = programs?.flatMap(p =>
    p.rounds.map(r => ({
      ...r,
      programId: p.id,
      programName: `${p.year} Edition`,
    }))
  ) || []

  // Set default selected round
  if (rounds.length && !selectedValue) {
    setSelectedValue(rounds[0].id)
  }

  const hasSelection = !!selectedValue
  const selectedRound = rounds.find((r) => r.id === selectedValue)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Reports</h1>
        <p className="text-muted-foreground">
          View evaluation progress and statistics
        </p>
      </div>

      {/* Round Selector */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
        <label className="text-sm font-medium">Select Round:</label>
        {roundsLoading ? (
          <Skeleton className="h-10 w-full sm:w-[300px]" />
        ) : rounds.length > 0 ? (
          <Select value={selectedValue || ''} onValueChange={setSelectedValue}>
            <SelectTrigger className="w-full sm:w-[300px]">
              <SelectValue placeholder="Select a round" />
            </SelectTrigger>
            <SelectContent>
              {programs?.map((p) => (
                <SelectItem key={`all:${p.id}`} value={`all:${p.id}`}>
                  {p.year} Edition — All Rounds
                </SelectItem>
              ))}
              {rounds.map((round) => (
                <SelectItem key={round.id} value={round.id}>
                  {round.programName} - {round.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : (
          <p className="text-sm text-muted-foreground">No rounds available</p>
        )}
      </div>

      {/* Tabs */}
      <Tabs defaultValue="overview" className="space-y-6">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <TabsList>
            <TabsTrigger value="overview" className="gap-2">
              <FileSpreadsheet className="h-4 w-4" />
              Overview
            </TabsTrigger>
            <TabsTrigger value="analytics" className="gap-2" disabled={!hasSelection}>
              <TrendingUp className="h-4 w-4" />
              Analytics
            </TabsTrigger>
            <TabsTrigger value="cross-round" className="gap-2">
              <GitCompare className="h-4 w-4" />
              Cross-Round
            </TabsTrigger>
            <TabsTrigger value="consistency" className="gap-2" disabled={!hasSelection}>
              <UserCheck className="h-4 w-4" />
              Juror Consistency
            </TabsTrigger>
            <TabsTrigger value="diversity" className="gap-2" disabled={!hasSelection}>
              <Globe className="h-4 w-4" />
              Diversity
            </TabsTrigger>
          </TabsList>
          {selectedValue && !selectedValue.startsWith('all:') && (
            <ExportPdfButton
              roundId={selectedValue}
              roundName={selectedRound?.name}
              programName={selectedRound?.programName}
            />
          )}
        </div>

        <TabsContent value="overview">
          <OverviewTab selectedValue={selectedValue} />
        </TabsContent>

        <TabsContent value="analytics">
          {hasSelection ? (
            <AnalyticsTab selectedValue={selectedValue!} />
          ) : (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <BarChart3 className="h-12 w-12 text-muted-foreground/50" />
                <p className="mt-2 font-medium">Select a round</p>
                <p className="text-sm text-muted-foreground">
                  Choose a round or edition from the dropdown above to view analytics
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="cross-round">
          <CrossRoundTab />
        </TabsContent>

        <TabsContent value="consistency">
          {hasSelection ? (
            <JurorConsistencyTab selectedValue={selectedValue!} />
          ) : (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <UserCheck className="h-12 w-12 text-muted-foreground/50" />
                <p className="mt-2 font-medium">Select a round</p>
                <p className="text-sm text-muted-foreground">
                  Choose a round or edition above to view juror consistency metrics
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="diversity">
          {hasSelection ? (
            <DiversityTab selectedValue={selectedValue!} />
          ) : (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <Globe className="h-12 w-12 text-muted-foreground/50" />
                <p className="mt-2 font-medium">Select a round</p>
                <p className="text-sm text-muted-foreground">
                  Choose a round or edition above to view diversity metrics
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}
