'use client'

import { useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  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 {
  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,
  Download,
  BarChart3,
  Users,
  ClipboardList,
  CheckCircle2,
  TrendingUp,
  GitCompare,
  UserCheck,
  Globe,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import {
  ScoreDistributionChart,
  EvaluationTimelineChart,
  StatusBreakdownChart,
  JurorWorkloadChart,
  ProjectRankingsChart,
  CriteriaScoresChart,
  GeographicDistribution,
  CrossRoundComparisonChart,
  JurorConsistencyChart,
  DiversityMetricsChart,
} from '@/components/charts'
import { ExportPdfButton } from '@/components/shared/export-pdf-button'

function ReportsOverview() {
  const { data: programs, isLoading } = trpc.program.list.useQuery({ includeRounds: true })
  const { data: dashStats, isLoading: statsLoading } = trpc.analytics.getDashboardStats.useQuery()

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

  if (isLoading || statsLoading) {
    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 totalPrograms = dashStats?.programCount ?? programs?.length ?? 0
  const totalProjects = dashStats?.projectCount ?? 0
  const activeRounds = dashStats?.activeRoundCount ?? rounds.filter((r) => r.status === 'ACTIVE').length
  const jurorCount = dashStats?.jurorCount ?? 0
  const submittedEvaluations = dashStats?.submittedEvaluations ?? 0
  const totalEvaluations = dashStats?.totalEvaluations ?? 0
  const completionRate = dashStats?.completionRate ?? 0

  return (
    <div className="space-y-6">
      {/* Quick Stats */}
      <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">Programs</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalPrograms}</div>
            <p className="text-xs text-muted-foreground">
              {activeRounds} active round{activeRounds !== 1 ? 's' : ''}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Projects</CardTitle>
            <ClipboardList className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalProjects}</div>
            <p className="text-xs text-muted-foreground">Across all programs</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Jury Members</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{jurorCount}</div>
            <p className="text-xs text-muted-foreground">Active 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>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{submittedEvaluations}</div>
            <p className="text-xs text-muted-foreground">
              {totalEvaluations > 0
                ? `${completionRate}% completion rate`
                : 'No assignments yet'}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Score Distribution (if any evaluations exist) */}
      {dashStats?.scoreDistribution && dashStats.scoreDistribution.some(b => b.count > 0) && (
        <Card>
          <CardHeader>
            <CardTitle>Score Distribution</CardTitle>
            <CardDescription>Overall score distribution across all evaluations</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {dashStats.scoreDistribution.map((bucket) => {
                const maxCount = Math.max(...dashStats.scoreDistribution.map(b => b.count), 1)
                return (
                  <div key={bucket.label} className="flex items-center gap-3">
                    <span className="w-10 text-sm font-medium text-right">{bucket.label}</span>
                    <div className="flex-1">
                      <Progress value={(bucket.count / maxCount) * 100} className="h-6" />
                    </div>
                    <span className="w-8 text-sm text-muted-foreground text-right">{bucket.count}</span>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Rounds Table */}
      <Card>
        <CardHeader>
          <CardTitle>Round Reports</CardTitle>
          <CardDescription>
            View progress and export data for each round
          </CardDescription>
        </CardHeader>
        <CardContent>
          {rounds.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <FileSpreadsheet className="h-10 w-10 text-muted-foreground/50" />
              <p className="mt-2 text-sm text-muted-foreground">
                No rounds created yet. Round-specific reports will appear here once rounds are set up.
              </p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Round</TableHead>
                  <TableHead>Program</TableHead>
                  <TableHead>Projects</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Export</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>-</TableCell>
                    <TableCell>
                      <Badge
                        variant={
                          round.status === 'ACTIVE'
                            ? 'default'
                            : round.status === 'CLOSED'
                              ? 'secondary'
                              : 'outline'
                        }
                      >
                        {round.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button variant="outline" size="sm" asChild>
                          <a
                            href={`/api/export/evaluations?roundId=${round.id}`}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            <Download className="mr-2 h-4 w-4" />
                            Evaluations
                          </a>
                        </Button>
                        <Button variant="outline" size="sm" asChild>
                          <a
                            href={`/api/export/results?roundId=${round.id}`}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            <Download className="mr-2 h-4 w-4" />
                            Results
                          </a>
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

function RoundAnalytics() {
  const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)

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

  // Flatten rounds from all programs with program name
  const rounds = programs?.flatMap(p => p.rounds.map(r => ({ ...r, programName: `${p.year} Edition` }))) || []

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

  const { data: scoreDistribution, isLoading: scoreLoading } =
    trpc.analytics.getScoreDistribution.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

  const { data: timeline, isLoading: timelineLoading } =
    trpc.analytics.getEvaluationTimeline.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

  const { data: statusBreakdown, isLoading: statusLoading } =
    trpc.analytics.getStatusBreakdown.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

  const { data: jurorWorkload, isLoading: workloadLoading } =
    trpc.analytics.getJurorWorkload.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

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

  const { data: criteriaScores, isLoading: criteriaLoading } =
    trpc.analytics.getCriteriaScores.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

  const selectedRound = rounds.find((r) => r.id === selectedRoundId)
  const { data: geoData, isLoading: geoLoading } =
    trpc.analytics.getGeographicDistribution.useQuery(
      { programId: selectedRound?.programId || '', roundId: selectedRoundId! },
      { enabled: !!selectedRoundId && !!selectedRound?.programId }
    )

  if (roundsLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-10 w-64" />
        <div className="grid gap-6 lg:grid-cols-2">
          <Skeleton className="h-[350px]" />
          <Skeleton className="h-[350px]" />
        </div>
      </div>
    )
  }

  if (!rounds?.length) {
    return (
      <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">No rounds available</p>
          <p className="text-sm text-muted-foreground">
            Create a round to view analytics
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      {/* Round Selector */}
      <div className="flex items-center gap-4">
        <label className="text-sm font-medium">Select Round:</label>
        <Select value={selectedRoundId || ''} onValueChange={setSelectedRoundId}>
          <SelectTrigger className="w-[300px]">
            <SelectValue placeholder="Select a round" />
          </SelectTrigger>
          <SelectContent>
            {rounds.map((round) => (
              <SelectItem key={round.id} value={round.id}>
                {round.programName} - {round.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {selectedRoundId && (
        <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>
          )}

          {/* Row 6: Geographic Distribution */}
          {geoLoading ? (
            <Skeleton className="h-[500px]" />
          ) : geoData?.length ? (
            <GeographicDistribution data={geoData} />
          ) : null}
        </div>
      )}
    </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">
      {/* Round selector */}
      <Card>
        <CardHeader>
          <CardTitle>Select Rounds to Compare</CardTitle>
          <CardDescription>
            Choose at least 2 rounds to compare metrics side by side
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {rounds.map((round) => {
              const isSelected = selectedRoundIds.includes(round.id)
              return (
                <Badge
                  key={round.id}
                  variant={isSelected ? '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>

      {/* Comparison charts */}
      {comparisonLoading && selectedRoundIds.length >= 2 && (
        <div className="space-y-6">
          <Skeleton className="h-[350px]" />
          <div className="grid gap-6 lg:grid-cols-2">
            <Skeleton className="h-[300px]" />
            <Skeleton className="h-[300px]" />
          </div>
        </div>
      )}

      {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() {
  const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)

  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` }))
  ) || []

  if (rounds.length && !selectedRoundId) {
    setSelectedRoundId(rounds[0].id)
  }

  const { data: consistency, isLoading: consistencyLoading } =
    trpc.analytics.getJurorConsistency.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

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

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <label className="text-sm font-medium">Select Round:</label>
        <Select value={selectedRoundId || ''} onValueChange={setSelectedRoundId}>
          <SelectTrigger className="w-[300px]">
            <SelectValue placeholder="Select a round" />
          </SelectTrigger>
          <SelectContent>
            {rounds.map((round) => (
              <SelectItem key={round.id} value={round.id}>
                {round.programName} - {round.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {consistencyLoading && <Skeleton className="h-[400px]" />}

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

function DiversityTab() {
  const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)

  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` }))
  ) || []

  if (rounds.length && !selectedRoundId) {
    setSelectedRoundId(rounds[0].id)
  }

  const { data: diversity, isLoading: diversityLoading } =
    trpc.analytics.getDiversityMetrics.useQuery(
      { roundId: selectedRoundId! },
      { enabled: !!selectedRoundId }
    )

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

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <label className="text-sm font-medium">Select Round:</label>
        <Select value={selectedRoundId || ''} onValueChange={setSelectedRoundId}>
          <SelectTrigger className="w-[300px]">
            <SelectValue placeholder="Select a round" />
          </SelectTrigger>
          <SelectContent>
            {rounds.map((round) => (
              <SelectItem key={round.id} value={round.id}>
                {round.programName} - {round.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {diversityLoading && <Skeleton className="h-[400px]" />}

      {diversity && (
        <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 }[]
          }}
        />
      )}
    </div>
  )
}

export default function ReportsPage() {
  const [pdfRoundId, setPdfRoundId] = useState<string | null>(null)

  const { data: pdfPrograms } = trpc.program.list.useQuery({ includeRounds: true })
  const pdfRounds = pdfPrograms?.flatMap((p) =>
    p.rounds.map((r) => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
  ) || []

  if (pdfRounds.length && !pdfRoundId) {
    setPdfRoundId(pdfRounds[0].id)
  }

  const selectedPdfRound = pdfRounds.find((r) => r.id === pdfRoundId)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Reports</h1>
        <p className="text-muted-foreground">
          View progress, analytics, and export evaluation data
        </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">
              <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">
              <UserCheck className="h-4 w-4" />
              Juror Consistency
            </TabsTrigger>
            <TabsTrigger value="diversity" className="gap-2">
              <Globe className="h-4 w-4" />
              Diversity
            </TabsTrigger>
          </TabsList>
          <div className="flex items-center gap-2">
            <Select value={pdfRoundId || ''} onValueChange={setPdfRoundId}>
              <SelectTrigger className="w-[220px]">
                <SelectValue placeholder="Select round for PDF" />
              </SelectTrigger>
              <SelectContent>
                {pdfRounds.map((round) => (
                  <SelectItem key={round.id} value={round.id}>
                    {round.programName} - {round.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {pdfRoundId && (
              <ExportPdfButton
                roundId={pdfRoundId}
                roundName={selectedPdfRound?.name}
                programName={selectedPdfRound?.programName}
              />
            )}
          </div>
        </div>

        <TabsContent value="overview">
          <ReportsOverview />
        </TabsContent>

        <TabsContent value="analytics">
          <RoundAnalytics />
        </TabsContent>

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

        <TabsContent value="consistency">
          <JurorConsistencyTab />
        </TabsContent>

        <TabsContent value="diversity">
          <DiversityTab />
        </TabsContent>
      </Tabs>
    </div>
  )
}
