'use client'

import { useState, useMemo } from 'react'
import { useDebounce } from '@/hooks/use-debounce'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Plus, Trophy, Users, CheckCircle2, Search } from 'lucide-react'
import { AnimatedCard } from '@/components/shared/animated-container'

const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  DRAFT: 'secondary',
  NOMINATIONS_OPEN: 'default',
  VOTING_OPEN: 'default',
  CLOSED: 'outline',
  ARCHIVED: 'secondary',
}

const SCORING_LABELS: Record<string, string> = {
  PICK_WINNER: 'Pick Winner',
  RANKED: 'Ranked',
  SCORED: 'Scored',
}

export default function AwardsListPage() {
  const { data: awards, isLoading } = trpc.specialAward.list.useQuery(
    {},
    { refetchInterval: 30_000 }
  )

  const [search, setSearch] = useState('')
  const debouncedSearch = useDebounce(search, 300)
  const [statusFilter, setStatusFilter] = useState('all')
  const [scoringFilter, setScoringFilter] = useState('all')

  const filteredAwards = useMemo(() => {
    if (!awards) return []
    return awards.filter((award) => {
      const matchesSearch =
        !debouncedSearch ||
        award.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        award.description?.toLowerCase().includes(debouncedSearch.toLowerCase())
      const matchesStatus = statusFilter === 'all' || award.status === statusFilter
      const matchesScoring = scoringFilter === 'all' || award.scoringMode === scoringFilter
      return matchesSearch && matchesStatus && matchesScoring
    })
  }, [awards, debouncedSearch, statusFilter, scoringFilter])

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="mt-2 h-4 w-72" />
          </div>
          <Skeleton className="h-9 w-32" />
        </div>
        {/* Toolbar skeleton */}
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <Skeleton className="h-10 flex-1" />
          <div className="flex items-center gap-2">
            <Skeleton className="h-10 w-[180px]" />
            <Skeleton className="h-10 w-[160px]" />
          </div>
        </div>
        {/* Cards skeleton */}
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[...Array(6)].map((_, i) => (
            <Skeleton key={i} className="h-48 rounded-lg" />
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            Special Awards
          </h1>
          <p className="text-muted-foreground">
            Manage named awards with eligibility criteria and jury voting
          </p>
        </div>
        <Button asChild>
          <Link href="/admin/awards/new">
            <Plus className="mr-2 h-4 w-4" />
            Create Award
          </Link>
        </Button>
      </div>

      {/* Toolbar */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <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 awards..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex items-center gap-2">
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All statuses</SelectItem>
              <SelectItem value="DRAFT">Draft</SelectItem>
              <SelectItem value="NOMINATIONS_OPEN">Nominations Open</SelectItem>
              <SelectItem value="VOTING_OPEN">Voting Open</SelectItem>
              <SelectItem value="CLOSED">Closed</SelectItem>
              <SelectItem value="ARCHIVED">Archived</SelectItem>
            </SelectContent>
          </Select>
          <Select value={scoringFilter} onValueChange={setScoringFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue placeholder="All scoring" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All scoring</SelectItem>
              <SelectItem value="PICK_WINNER">Pick Winner</SelectItem>
              <SelectItem value="RANKED">Ranked</SelectItem>
              <SelectItem value="SCORED">Scored</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Results count */}
      {awards && (
        <p className="text-sm text-muted-foreground">
          {filteredAwards.length} of {awards.length} awards
        </p>
      )}

      {/* Awards Grid */}
      {filteredAwards.length > 0 ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filteredAwards.map((award, index) => (
            <AnimatedCard key={award.id} index={index}>
            <Link href={`/admin/awards/${award.id}`}>
              <Card className="transition-all duration-200 hover:bg-muted/50 hover:-translate-y-0.5 hover:shadow-md cursor-pointer h-full">
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Trophy className="h-5 w-5 text-amber-500" />
                      {award.name}
                    </CardTitle>
                    <Badge variant={STATUS_COLORS[award.status] || 'secondary'}>
                      {award.status.replace(/_/g, ' ')}
                    </Badge>
                  </div>
                  {award.description && (
                    <CardDescription className="line-clamp-2">
                      {award.description}
                    </CardDescription>
                  )}
                </CardHeader>
                <CardContent>
                  <div className="flex items-center gap-4 text-sm text-muted-foreground">
                    <div className="flex items-center gap-1">
                      <CheckCircle2 className="h-4 w-4" />
                      {award._count.eligibilities} eligible
                    </div>
                    <div className="flex items-center gap-1">
                      <Users className="h-4 w-4" />
                      {award._count.jurors} jurors
                    </div>
                    <Badge variant="outline" className="text-xs">
                      {SCORING_LABELS[award.scoringMode] || award.scoringMode}
                    </Badge>
                  </div>
                  {award.winnerProject && (
                    <div className="mt-3 pt-3 border-t">
                      <p className="text-sm">
                        <span className="text-muted-foreground">Winner:</span>{' '}
                        <span className="font-medium">
                          {award.winnerProject.title}
                        </span>
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>
            </Link>
            </AnimatedCard>
          ))}
        </div>
      ) : awards && awards.length > 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-8 text-center">
            <Search className="h-8 w-8 text-muted-foreground/40" />
            <p className="mt-2 text-sm text-muted-foreground">
              No awards match your filters
            </p>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Trophy className="h-12 w-12 text-muted-foreground/40" />
            <h3 className="mt-3 text-lg font-medium">No awards yet</h3>
            <p className="mt-1 text-sm text-muted-foreground max-w-sm">
              Create special awards with eligibility criteria and jury voting for outstanding projects.
            </p>
            <Button className="mt-4" asChild>
              <Link href="/admin/awards/new">
                <Plus className="mr-2 h-4 w-4" />
                Create Award
              </Link>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
