'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,
  CrossStageComparisonChart,
  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({ includeStages: true })

  const stages = programs?.flatMap(p =>
    (p.stages as { id: string; name: string; status: string; windowCloseAt: Date | null; _count: { projects: number; assignments: number } }[]).map(s => ({
      ...s,
      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 = stages.reduce((acc, s) => acc + (s._count?.projects || 0), 0)
  const activeStages = stages.filter((s) => s.status === 'ROUND_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 Stages</p>
                  <p className="text-2xl font-bold mt-1">{stages.length}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {activeStages} 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 stages</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 Stages</p>
                  <p className="text-2xl font-bold mt-1">{activeStages}</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}
        </>
      )}

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

      {/* Stages Cards - Mobile */}
      <div className="space-y-4 md:hidden">
        <h2 className="text-lg font-semibold">Stage Reports</h2>
        {stages.map((stage) => (
          <Card key={stage.id}>
            <CardContent className="pt-4 space-y-3">
              <div className="flex items-center justify-between">
                <p className="font-medium">{stage.name}</p>
                <Badge
                  variant={
                    stage.status === 'STAGE_ACTIVE'
                      ? 'default'
                      : stage.status === 'STAGE_CLOSED'
                        ? 'secondary'
                        : 'outline'
                  }
                >
                  {stage.status === 'STAGE_ACTIVE' ? 'Active' : stage.status === 'STAGE_CLOSED' ? 'Closed' : stage.status}
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">{stage.programName}</p>
              {stage.windowCloseAt && (
                <p className="text-xs text-muted-foreground">
                  Ends: {formatDateOnly(stage.windowCloseAt)}
                </p>
              )}
              <div className="text-sm">
                <span>{stage._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 CrossStageTab() {
  const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeStages: true })

  const stages = programs?.flatMap(p =>
    ((p.stages || []) as Array<{ id: string; name: string }>).map(s => ({ id: s.id, name: s.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 Stages to Compare</CardTitle>
          <CardDescription>Choose at least 2 stages</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {stages.map((stage) => (
              <Badge
                key={stage.id}
                variant={selectedRoundIds.includes(stage.id) ? 'default' : 'outline'}
                className="cursor-pointer text-sm py-1.5 px-3"
                onClick={() => toggleRound(stage.id)}
              >
                {stage.programName} - {stage.name}
              </Badge>
            ))}
          </div>
          {selectedRoundIds.length < 2 && (
            <p className="text-sm text-muted-foreground mt-3">
              Select at least 2 stages to enable comparison
            </p>
          )}
        </CardContent>
      </Card>

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

      {comparison && (
        <CrossStageComparisonChart 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: stagesLoading } = trpc.program.list.useQuery({ includeStages: true })

  const stages = programs?.flatMap(p =>
    (p.stages as { id: string; name: string; status: string; windowCloseAt: Date | null; _count: { projects: number; assignments: number } }[]).map(s => ({
      ...s,
      programId: p.id,
      programName: `${p.year} Edition`,
    }))
  ) || []

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

  const hasSelection = !!selectedValue
  const selectedRound = stages.find((s) => s.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>

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