'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
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 { Input } from '@/components/ui/input'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { StatusBadge } from '@/components/shared/status-badge'
import {
  FolderKanban,
  ClipboardList,
  Users,
  CheckCircle2,
  Eye,
  BarChart3,
  Search,
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { AnimatedCard } from '@/components/shared/animated-container'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
import { useDebouncedCallback } from 'use-debounce'

const PER_PAGE_OPTIONS = [10, 20, 50]

export function ObserverDashboardContent({ userName }: { userName?: string }) {
  const [selectedRoundId, setSelectedRoundId] = useState<string>('all')
  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [sortBy, setSortBy] = useState<'title' | 'score' | 'evaluations'>('title')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc')
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState(20)

  const debouncedSetSearch = useDebouncedCallback((value: string) => {
    setDebouncedSearch(value)
    setPage(1)
  }, 300)

  const handleSearchChange = (value: string) => {
    setSearch(value)
    debouncedSetSearch(value)
  }

  const handleRoundChange = (value: string) => {
    setSelectedRoundId(value)
    setPage(1)
  }

  const handleStatusChange = (value: string) => {
    setStatusFilter(value)
    setPage(1)
  }

  const handleSort = (column: 'title' | 'score' | 'evaluations') => {
    if (sortBy === column) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(column)
      setSortDir(column === 'title' ? 'asc' : 'desc')
    }
    setPage(1)
  }

  const SortIcon = ({ column }: { column: 'title' | 'score' | 'evaluations' }) => {
    if (sortBy !== column) return <ArrowUpDown className="ml-1 inline h-3 w-3 text-muted-foreground/50" />
    return sortDir === 'asc'
      ? <ArrowUp className="ml-1 inline h-3 w-3" />
      : <ArrowDown className="ml-1 inline h-3 w-3" />
  }

  // Fetch programs/rounds for the filter dropdown
  const { data: programs } = trpc.program.list.useQuery({ includeStages: true })

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

  // Default to the active round
  useEffect(() => {
    if (rounds.length && selectedRoundId === 'all') {
      const active = rounds.find((r) => r.status === 'ROUND_ACTIVE')
      if (active) setSelectedRoundId(active.id)
    }
  }, [rounds.length]) // eslint-disable-line react-hooks/exhaustive-deps

  // Fetch dashboard stats
  const roundIdParam = selectedRoundId !== 'all' ? selectedRoundId : undefined
  const { data: stats, isLoading: statsLoading } = trpc.analytics.getDashboardStats.useQuery(
    { roundId: roundIdParam }
  )

  // Fetch projects
  const { data: projectsData, isLoading: projectsLoading } = trpc.analytics.getAllProjects.useQuery({
    roundId: roundIdParam,
    search: debouncedSearch || undefined,
    status: statusFilter !== 'all' ? statusFilter : undefined,
    sortBy,
    sortDir,
    page,
    perPage,
  })

  // Recent rounds for jury completion (reuse existing programs data)
  const recentRounds = rounds.slice(0, 5)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Dashboard</h1>
        <p className="text-muted-foreground">
          Welcome, {userName || 'Observer'}
        </p>
      </div>

      {/* Round Filter */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
        <label className="text-sm font-medium">Filter by Round:</label>
        <Select value={selectedRoundId} onValueChange={handleRoundChange}>
          <SelectTrigger className="w-full sm:w-[300px]">
            <SelectValue placeholder="All Rounds" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Rounds</SelectItem>
            {rounds.map((round) => (
              <SelectItem key={round.id} value={round.id}>
                {round.name}{round.roundType ? ` (${round.roundType.replace(/_/g, ' ')})` : ''}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Stats Grid */}
      {statsLoading ? (
        <div className="grid gap-4 md: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>
      ) : stats ? (
        <div className="space-y-4">
          {/* Universal stats: Programs + Projects */}
          <div className="grid gap-4 md:grid-cols-2">
            <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">Programs</p>
                      <p className="text-2xl font-bold mt-1">{stats.programCount}</p>
                      <p className="text-xs text-muted-foreground mt-1">
                        {stats.activeRoundCount} active round{stats.activeRoundCount !== 1 ? 's' : ''}
                      </p>
                    </div>
                    <div className="rounded-xl bg-blue-50 p-3">
                      <FolderKanban 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">Projects</p>
                      <p className="text-2xl font-bold mt-1">{stats.projectCount}</p>
                      <p className="text-xs text-muted-foreground mt-1">
                        {selectedRoundId !== 'all' ? 'In selected round' : '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>
          </div>

          {/* Round-type-aware stats */}
          {selectedRoundId !== 'all' ? (
            <RoundTypeStatsCards roundId={selectedRoundId} />
          ) : (
            <div className="grid gap-4 md:grid-cols-2">
              <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">Jury Members</p>
                        <p className="text-2xl font-bold mt-1">{stats.jurorCount}</p>
                        <p className="text-xs text-muted-foreground mt-1">Active members</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">Evaluations</p>
                        <p className="text-2xl font-bold mt-1">{stats.submittedEvaluations}</p>
                        <div className="mt-2">
                          <Progress value={stats.completionRate} className="h-2" gradient />
                          <p className="mt-1 text-xs text-muted-foreground">
                            {stats.completionRate}% completion rate
                          </p>
                        </div>
                      </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>
          )}
        </div>
      ) : null}

      {/* Projects Table */}
      <AnimatedCard index={4}>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2.5">
            <div className="rounded-lg bg-emerald-500/10 p-1.5">
              <ClipboardList className="h-4 w-4 text-emerald-500" />
            </div>
            All Projects
          </CardTitle>
          <CardDescription>
            {projectsData ? `${projectsData.total} project${projectsData.total !== 1 ? 's' : ''} found` : 'Loading projects...'}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Search & Filter Bar */}
          <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search by title or team..."
                value={search}
                onChange={(e) => handleSearchChange(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={statusFilter} onValueChange={handleStatusChange}>
              <SelectTrigger className="w-full sm:w-[180px]">
                <SelectValue placeholder="All Statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                <SelectItem value="SUBMITTED">Submitted</SelectItem>
                <SelectItem value="ELIGIBLE">Eligible</SelectItem>
                <SelectItem value="ASSIGNED">Assigned</SelectItem>
                <SelectItem value="SEMIFINALIST">Semi-finalist</SelectItem>
                <SelectItem value="FINALIST">Finalist</SelectItem>
                <SelectItem value="REJECTED">Rejected</SelectItem>
              </SelectContent>
            </Select>
            <Select value={String(perPage)} onValueChange={(v) => { setPerPage(Number(v)); setPage(1) }}>
              <SelectTrigger className="w-full sm:w-[100px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {PER_PAGE_OPTIONS.map((n) => (
                  <SelectItem key={n} value={String(n)}>{n} / page</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {projectsLoading ? (
            <div className="space-y-2">
              {[...Array(5)].map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : projectsData && projectsData.projects.length > 0 ? (
            <>
              {/* Desktop Table */}
              <div className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>
                        <button type="button" onClick={() => handleSort('title')} className="inline-flex items-center hover:text-foreground transition-colors">
                          Title<SortIcon column="title" />
                        </button>
                      </TableHead>
                      <TableHead>Round</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="text-right">
                        <button type="button" onClick={() => handleSort('score')} className="inline-flex items-center hover:text-foreground transition-colors">
                          Avg Score<SortIcon column="score" />
                        </button>
                      </TableHead>
                      <TableHead className="text-right">
                        <button type="button" onClick={() => handleSort('evaluations')} className="inline-flex items-center hover:text-foreground transition-colors">
                          Evaluations<SortIcon column="evaluations" />
                        </button>
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {projectsData.projects.map((project) => (
                      <TableRow key={project.id} className="cursor-pointer hover:bg-muted/50" onClick={() => window.location.href = `/observer/projects/${project.id}`}>
                        <TableCell className="font-medium max-w-[300px] truncate">
                          <Link href={`/observer/projects/${project.id}` as Route} className="hover:underline" onClick={(e) => e.stopPropagation()}>
                            {project.title}
                          </Link>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="text-xs whitespace-nowrap">
                            {project.roundName}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={project.status} />
                        </TableCell>
                        <TableCell className="text-right tabular-nums">
                          {project.averageScore !== null
                            ? project.averageScore.toFixed(2)
                            : '-'}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">
                          {project.evaluationCount}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* Mobile Cards */}
              <div className="space-y-3 md:hidden">
                {projectsData.projects.map((project) => (
                  <Link key={project.id} href={`/observer/projects/${project.id}` as Route}>
                    <Card className="transition-colors hover:bg-muted/50">
                      <CardContent className="pt-4 space-y-2">
                        <div className="flex items-start justify-between gap-2">
                          <p className="font-medium text-sm leading-tight">{project.title}</p>
                          <StatusBadge status={project.status} />
                        </div>
                        <div className="flex items-center justify-between text-xs text-muted-foreground">
                          <Badge variant="outline" className="text-xs">
                            {project.roundName}
                          </Badge>
                          <div className="flex gap-3">
                            <span>Score: {project.averageScore !== null ? project.averageScore.toFixed(2) : '-'}</span>
                            <span>{project.evaluationCount} eval{project.evaluationCount !== 1 ? 's' : ''}</span>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </Link>
                ))}
              </div>

              {/* Pagination */}
              {projectsData.totalPages > 1 && (
                <div className="flex items-center justify-between pt-2">
                  <p className="text-sm text-muted-foreground">
                    Page {projectsData.page} of {projectsData.totalPages}
                  </p>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                      disabled={page <= 1}
                    >
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage((p) => Math.min(projectsData.totalPages, p + 1))}
                      disabled={page >= projectsData.totalPages}
                    >
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <ClipboardList className="h-12 w-12 text-muted-foreground/50" />
              <p className="mt-2 text-sm text-muted-foreground">
                {debouncedSearch || statusFilter !== 'all'
                  ? 'No projects match your filters'
                  : 'No projects found'}
              </p>
            </div>
          )}
        </CardContent>
      </Card>
      </AnimatedCard>

      {/* Score Distribution */}
      {stats && stats.scoreDistribution.some((b) => b.count > 0) && (
        <AnimatedCard index={5}>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2.5">
              <div className="rounded-lg bg-amber-500/10 p-1.5">
                <BarChart3 className="h-4 w-4 text-amber-500" />
              </div>
              Score Distribution
            </CardTitle>
            <CardDescription>Distribution of global scores across evaluations</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {(() => {
                const maxCount = Math.max(...stats.scoreDistribution.map((b) => b.count), 1)
                // Score-based colors: high scores = brand dark blue, low = brand red
                const scoreColors: Record<string, string> = {
                  '9-10': '#053d57',
                  '7-8': '#1e7a8a',
                  '5-6': '#557f8c',
                  '3-4': '#c4453a',
                  '1-2': '#de0f1e',
                }
                return stats.scoreDistribution.map((bucket) => (
                  <div key={bucket.label} className="flex items-center gap-3" role="img" aria-label={`Score ${bucket.label}: ${bucket.count} evaluations`}>
                    <span className="text-sm w-16 text-right tabular-nums">{bucket.label}</span>
                    <div className="flex-1 h-6 bg-muted rounded-full overflow-hidden">
                      <div
                        className="h-full rounded-full transition-all"
                        style={{
                          width: `${maxCount > 0 ? (bucket.count / maxCount) * 100 : 0}%`,
                          backgroundColor: scoreColors[bucket.label] || '#557f8c',
                        }}
                      />
                    </div>
                    <span className="text-sm tabular-nums w-8">{bucket.count}</span>
                  </div>
                ))
              })()}
            </div>
          </CardContent>
        </Card>
        </AnimatedCard>
      )}

      {/* Recent Rounds */}
      {recentRounds.length > 0 && (
        <AnimatedCard index={6}>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2.5">
              <div className="rounded-lg bg-violet-500/10 p-1.5">
                <BarChart3 className="h-4 w-4 text-violet-500" />
              </div>
              Recent Rounds
            </CardTitle>
            <CardDescription>Overview of the latest evaluation rounds</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {recentRounds.map((round) => (
                <Link
                  key={round.id}
                  href={`/observer/reports?round=${round.id}`}
                  className="flex items-center justify-between rounded-lg border p-4 transition-all hover:shadow-sm hover:bg-muted/50"
                >
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <p className="font-medium">{round.name}</p>
                      {round.roundType && (
                        <Badge variant="outline" className="text-xs">
                          {round.roundType.replace(/_/g, ' ')}
                        </Badge>
                      )}
                      <Badge
                        variant={
                          round.status === 'ROUND_ACTIVE'
                            ? 'default'
                            : round.status === 'ROUND_CLOSED'
                              ? 'secondary'
                              : 'outline'
                        }
                      >
                        {round.status === 'ROUND_ACTIVE' ? 'Active' : round.status === 'ROUND_CLOSED' ? 'Closed' : round.status}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {round.programName}
                    </p>
                  </div>
                  <ChevronRight className="h-5 w-5 text-muted-foreground" />
                </Link>
              ))}
            </div>
          </CardContent>
        </Card>
        </AnimatedCard>
      )}
    </div>
  )
}
