'use client'

import { useState, useEffect, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Globe,
  LayoutDashboard,
  Filter,
  FolderOpen,
  TrendingUp,
  Users,
  BarChart3,
  Upload,
  Presentation,
  Vote,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'

import { GlobalAnalyticsTab } from '@/components/observer/reports/global-analytics-tab'
import { IntakeReportTabs } from '@/components/observer/reports/intake-report-tabs'
import { FilteringReportTabs } from '@/components/observer/reports/filtering-report-tabs'
import { EvaluationReportTabs } from '@/components/observer/reports/evaluation-report-tabs'
import { SubmissionReportTabs } from '@/components/observer/reports/submission-report-tabs'
import { MentoringReportTabs } from '@/components/observer/reports/mentoring-report-tabs'
import { LiveFinalReportTabs } from '@/components/observer/reports/live-final-report-tabs'
import { DeliberationReportTabs } from '@/components/observer/reports/deliberation-report-tabs'

const ROUND_TYPE_LABELS: Record<string, string> = {
  INTAKE: 'Intake',
  FILTERING: 'Filtering',
  EVALUATION: 'Evaluation',
  SUBMISSION: 'Submission',
  MENTORING: 'Mentoring',
  LIVE_FINAL: 'Live Final',
  DELIBERATION: 'Deliberation',
}

type Stage = {
  id: string
  name: string
  status: string
  roundType: string
  windowCloseAt: Date | null
  _count: { projects: number; assignments: number; evaluations: number }
  programId: string
  programName: string
}

type TabDef = { value: string; label: string; icon: LucideIcon }

function getRoundTabs(roundType: string): TabDef[] {
  switch (roundType) {
    case 'INTAKE':
      return [{ value: 'overview', label: 'Overview', icon: LayoutDashboard }]
    case 'FILTERING':
      return [
        { value: 'screening', label: 'Screening', icon: Filter },
      ]
    case 'EVALUATION':
      return [
        { value: 'evaluation', label: 'Evaluation', icon: TrendingUp },
      ]
    case 'SUBMISSION':
      return [{ value: 'overview', label: 'Overview', icon: Upload }]
    case 'MENTORING':
      return [{ value: 'overview', label: 'Overview', icon: Users }]
    case 'LIVE_FINAL':
      return [{ value: 'session', label: 'Session', icon: Presentation }]
    case 'DELIBERATION':
      return [
        { value: 'deliberation', label: 'Deliberation', icon: Vote },
      ]
    default:
      return []
  }
}

function RoundTypeContent({
  roundType,
  roundId,
  programId,
  stages,
  selectedValue,
}: {
  roundType: string
  roundId: string
  programId: string
  stages: Stage[]
  selectedValue: string | null
}) {
  switch (roundType) {
    case 'INTAKE':
      return <IntakeReportTabs roundId={roundId} programId={programId} />
    case 'FILTERING':
      return <FilteringReportTabs roundId={roundId} programId={programId} />
    case 'EVALUATION':
      return (
        <EvaluationReportTabs
          roundId={roundId}
          programId={programId}
          stages={stages}
          selectedValue={selectedValue}
        />
      )
    case 'SUBMISSION':
      return <SubmissionReportTabs roundId={roundId} programId={programId} />
    case 'MENTORING':
      return <MentoringReportTabs roundId={roundId} programId={programId} />
    case 'LIVE_FINAL':
      return <LiveFinalReportTabs roundId={roundId} programId={programId} />
    case 'DELIBERATION':
      return <DeliberationReportTabs roundId={roundId} programId={programId} />
    default:
      return null
  }
}

function ReportsPageContent() {
  const searchParams = useSearchParams()
  const roundFromUrl = searchParams.get('round')
  const [selectedValue, setSelectedValue] = useState<string | null>(roundFromUrl)
  const [activeTab, setActiveTab] = useState<string | null>(null)

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

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

  const allRoundIds = stages.map((s) => s.id)

  useEffect(() => {
    if (stages.length && !selectedValue) {
      const active = stages.find((s) => s.status === 'ROUND_ACTIVE')
      setSelectedValue(active ? active.id : stages[0].id)
    }
  }, [stages.length, selectedValue])

  // Reset to first round-specific tab when round selection changes
  useEffect(() => {
    setActiveTab(null)
  }, [selectedValue])

  const isAllRounds = selectedValue?.startsWith('all:')
  const selectedRound = stages.find((s) => s.id === selectedValue)
  const roundType = selectedRound?.roundType ?? ''
  const programId = isAllRounds
    ? selectedValue!.slice(4)
    : selectedRound?.programId ?? programs?.[0]?.id ?? ''

  const roundSpecificTabs = isAllRounds
    ? [{ value: 'progress', label: 'Progress', icon: TrendingUp }]
    : getRoundTabs(roundType)

  const allTabs: TabDef[] = [
    ...roundSpecificTabs,
    { value: 'global', label: 'Global', icon: Globe },
  ]

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

      <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>
        {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 round" />
            </SelectTrigger>
            <SelectContent>
              {programs?.map((p) => (
                <SelectItem key={`all:${p.id}`} value={`all:${p.id}`}>
                  {p.year} Edition — All Rounds
                </SelectItem>
              ))}
              {stages.map((stage) => (
                <SelectItem key={stage.id} value={stage.id}>
                  {stage.name}{stage.roundType ? ` (${ROUND_TYPE_LABELS[stage.roundType] || stage.roundType})` : ''}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : (
          <p className="text-sm text-muted-foreground">No rounds available</p>
        )}
      </div>

      {selectedValue && (
        <Tabs value={activeTab ?? allTabs[0]?.value ?? 'global'} onValueChange={setActiveTab} className="space-y-6">
          <TabsList>
            {allTabs.map((tab) => (
              <TabsTrigger key={tab.value} value={tab.value} className="gap-2">
                <tab.icon className="h-4 w-4" />
                {tab.label}
              </TabsTrigger>
            ))}
          </TabsList>

          <TabsContent value="global">
            <GlobalAnalyticsTab
              programId={programId}
              roundIds={allRoundIds.length >= 2 ? allRoundIds : undefined}
            />
          </TabsContent>

          {/* Round-type-specific or "All Rounds" progress tab */}
          {roundSpecificTabs.map((tab) => (
            <TabsContent key={tab.value} value={tab.value}>
              {isAllRounds ? (
                <EvaluationReportTabs
                  roundId=""
                  programId={programId}
                  stages={stages}
                  selectedValue={selectedValue}
                />
              ) : selectedRound ? (
                <RoundTypeContent
                  roundType={roundType}
                  roundId={selectedRound.id}
                  programId={programId}
                  stages={stages}
                  selectedValue={selectedValue}
                />
              ) : null}
            </TabsContent>
          ))}
        </Tabs>
      )}
    </div>
  )
}

export default function ObserverReportsPage() {
  return (
    <Suspense
      fallback={
        <div className="space-y-6">
          <div>
            <Skeleton className="h-8 w-32" />
            <Skeleton className="mt-2 h-4 w-56" />
          </div>
          <Skeleton className="h-10 w-full sm:w-[300px]" />
          <Skeleton className="h-[400px] w-full" />
        </div>
      }
    >
      <ReportsPageContent />
    </Suspense>
  )
}
