'use client'

import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Plus,
  Medal,
  Calendar,
  Users,
  Layers,
  FileBox,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { formatDistanceToNow } from 'date-fns'
import { useEdition } from '@/contexts/edition-context'

const statusConfig = {
  DRAFT: {
    label: 'Draft',
    bgClass: 'bg-gray-100 text-gray-700',
    dotClass: 'bg-gray-500',
  },
  ACTIVE: {
    label: 'Active',
    bgClass: 'bg-emerald-100 text-emerald-700',
    dotClass: 'bg-emerald-500',
  },
  CLOSED: {
    label: 'Closed',
    bgClass: 'bg-blue-100 text-blue-700',
    dotClass: 'bg-blue-500',
  },
  ARCHIVED: {
    label: 'Archived',
    bgClass: 'bg-muted text-muted-foreground',
    dotClass: 'bg-muted-foreground',
  },
} as const

export default function CompetitionListPage() {
  const { currentEdition } = useEdition()
  const programId = currentEdition?.id

  const { data: competitions, isLoading } = trpc.competition.list.useQuery(
    { programId: programId! },
    { enabled: !!programId }
  )

  if (!programId) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Competitions</h1>
            <p className="text-sm text-muted-foreground">
              Select an edition to view competitions
            </p>
          </div>
        </div>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Calendar className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No Edition Selected</p>
            <p className="text-sm text-muted-foreground">
              Select an edition from the sidebar to view its competitions
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
      <div className="space-y-6 px-4 sm:px-0">
        {/* Header */}
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-bold">Competitions</h1>
          <p className="text-sm text-muted-foreground">
            Manage competitions for {currentEdition?.name}
          </p>
        </div>
        <Link href={`/admin/competitions/new?programId=${programId}` as Route}>
          <Button size="sm" className="w-full sm:w-auto">
            <Plus className="h-4 w-4 mr-1" />
            New Competition
          </Button>
        </Link>
      </div>

      {/* Loading */}
      {isLoading && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardHeader>
                <Skeleton className="h-5 w-32" />
                <Skeleton className="h-4 w-20 mt-1" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4 mt-2" />
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!isLoading && (!competitions || competitions.length === 0) && (
        <Card className="border-2 border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-16 text-center">
            <div className="rounded-full bg-primary/10 p-4 mb-4">
              <Medal className="h-10 w-10 text-primary" />
            </div>
            <h3 className="text-lg font-semibold mb-2">No Competitions Yet</h3>
            <p className="text-sm text-muted-foreground max-w-md mb-6">
              Competitions organize your multi-round evaluation workflow with jury groups,
              submission windows, and scoring. Create your first competition to get started.
            </p>
            <Link href={`/admin/competitions/new?programId=${programId}` as Route}>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Create Your First Competition
              </Button>
            </Link>
          </CardContent>
        </Card>
      )}

      {/* Competition Cards */}
      {competitions && competitions.length > 0 && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {competitions.map((competition) => {
            const status = competition.status as keyof typeof statusConfig
            const config = statusConfig[status] || statusConfig.DRAFT

            return (
              <Link key={competition.id} href={`/admin/competitions/${competition.id}` as Route}>
                <Card className="group cursor-pointer hover:shadow-md transition-shadow h-full flex flex-col">
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0 flex-1">
                        <CardTitle className="text-base leading-tight">
                          {competition.name}
                        </CardTitle>
                        <p className="text-xs text-muted-foreground mt-1 font-mono">
                          {competition.slug}
                        </p>
                      </div>
                      <Badge
                        variant="secondary"
                        className={cn(
                          'text-[10px] shrink-0 flex items-center gap-1.5',
                          config.bgClass
                        )}
                      >
                        <span className={cn('h-1.5 w-1.5 rounded-full', config.dotClass)} />
                        {config.label}
                      </Badge>
                    </div>
                  </CardHeader>

                  <CardContent className="mt-auto">
                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
                      <div className="flex items-center gap-1.5">
                        <Layers className="h-3.5 w-3.5" />
                        <span>{competition._count.rounds} rounds</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Users className="h-3.5 w-3.5" />
                        <span>{competition._count.juryGroups} juries</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <FileBox className="h-3.5 w-3.5" />
                        <span>{competition._count.submissionWindows} windows</span>
                      </div>
                    </div>
                    <div className="mt-2 text-xs text-muted-foreground">
                      Updated {formatDistanceToNow(new Date(competition.updatedAt))} ago
                    </div>
                  </CardContent>
                </Card>
              </Link>
            )
          })}
        </div>
      )}
    </div>
  )
}
