'use client'

import Link from 'next/link'
import type { Route } from 'next'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { StatusBadge } from '@/components/shared/status-badge'
import { ProjectLogo } from '@/components/shared/project-logo'
import {
  ArrowLeft,
  ArrowRight,
  ClipboardList,
  CheckCircle2,
  Clock,
  FileEdit,
} from 'lucide-react'
import { formatDateOnly, formatEnumLabel } from '@/lib/utils'
import { CountryDisplay } from '@/components/shared/country-display'

export default function JuryAssignmentsPage() {
  const router = useRouter()
  const { data: assignments, isLoading } = trpc.assignment.myAssignments.useQuery({})

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-64" />
        <div className="space-y-3">
          {[1, 2, 3, 4].map((i) => (
            <Skeleton key={i} className="h-24 w-full rounded-xl" />
          ))}
        </div>
      </div>
    )
  }

  // Group assignments by round
  const byRound = new Map<string, { round: { id: string; name: string; roundType: string; status: string; windowCloseAt: Date | null }; items: typeof assignments }>()
  for (const a of assignments ?? []) {
    if (!a.round) continue
    if (!byRound.has(a.round.id)) {
      byRound.set(a.round.id, { round: a.round, items: [] })
    }
    byRound.get(a.round.id)!.items!.push(a)
  }

  const roundGroups = Array.from(byRound.values())

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-brand-blue">
            My Assignments
          </h1>
          <p className="text-muted-foreground mt-1">
            Projects assigned to you for evaluation
          </p>
        </div>
        <Button variant="ghost" size="sm" onClick={() => router.back()} className="hidden md:inline-flex">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
      </div>

      {roundGroups.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <div className="rounded-2xl bg-brand-teal/10 p-4 mb-4">
              <ClipboardList className="h-8 w-8 text-brand-teal/60" />
            </div>
            <h2 className="text-xl font-semibold mb-2">No Assignments</h2>
            <p className="text-muted-foreground text-center max-w-md">
              You don&apos;t have any assignments yet. Assignments will appear once an administrator assigns projects to you.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-6">
          {roundGroups.map(({ round, items }) => {
            const completed = (items ?? []).filter(
              (a) => a.evaluation?.status === 'SUBMITTED'
            ).length
            const total = items?.length ?? 0

            return (
              <Card key={round.id}>
                <CardHeader className="pb-3">
                  <div className="flex flex-wrap items-center gap-2">
                    <CardTitle className="text-base">{round.name}</CardTitle>
                    <Badge variant="secondary" className="text-xs shrink-0">
                      {formatEnumLabel(round.roundType)}
                    </Badge>
                    {round.status !== 'ROUND_ACTIVE' && (
                      <Badge variant="outline" className="text-xs text-muted-foreground shrink-0">
                        {formatEnumLabel(round.status)}
                      </Badge>
                    )}
                    <span className="text-xs text-muted-foreground ml-auto shrink-0">
                      {completed}/{total} completed
                    </span>
                    {round.windowCloseAt && (
                      <Badge variant="outline" className="text-xs gap-1 shrink-0">
                        <Clock className="h-3 w-3" />
                        Due {formatDateOnly(round.windowCloseAt)}
                      </Badge>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="divide-y">
                    {(items ?? []).map((assignment) => {
                      const project = assignment.project
                      const evalStatus = assignment.evaluation?.status
                      const isSubmitted = evalStatus === 'SUBMITTED'
                      const isDraft = evalStatus === 'DRAFT'

                      return (
                        <Link
                          key={assignment.id}
                          href={`/jury/competitions/${round.id}/projects/${project.id}` as Route}
                          className="block"
                        >
                          <div className="flex items-center gap-3 py-3 px-1 transition-colors hover:bg-muted/40 rounded-lg group">
                            <ProjectLogo
                              project={project}
                              size="sm"
                              fallback="initials"
                            />
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-medium truncate group-hover:text-brand-blue transition-colors">
                                {project.title}
                              </p>
                              <p className="text-xs text-muted-foreground mt-0.5">
                                {project.teamName}{project.teamName && project.country ? ' · ' : ''}{project.country ? <CountryDisplay country={project.country} /> : ''}
                              </p>
                            </div>
                            <div className="flex items-center gap-2 shrink-0">
                              {isSubmitted ? (
                                <Badge variant="success" className="gap-1">
                                  <CheckCircle2 className="h-3 w-3" />
                                  Submitted
                                </Badge>
                              ) : isDraft ? (
                                <Badge variant="warning" className="gap-1">
                                  <FileEdit className="h-3 w-3" />
                                  Draft
                                </Badge>
                              ) : (
                                <Badge variant="secondary" className="gap-1">
                                  <Clock className="h-3 w-3" />
                                  Pending
                                </Badge>
                              )}
                              <ArrowRight className="h-4 w-4 text-muted-foreground group-hover:text-brand-blue transition-colors" />
                            </div>
                          </div>
                        </Link>
                      )
                    })}
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
