'use client'

import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { FilePreview } from '@/components/shared/file-viewer'
import { FileText, Download, ShieldAlert } from 'lucide-react'

/**
 * Read-only judge review of finalist grand-final documents. Self-resolves the
 * active program and self-gates on the `finalist.listReviewDocuments` FORBIDDEN
 * check, so it can be mounted on any route reachable by either the finals jury
 * (`/jury/finals-documents`) or program admins (`/admin/finals-documents`).
 */
export function FinalsDocumentsReview() {
  const { data: programId, isLoading: programLoading } =
    trpc.competition.getActiveProgramId.useQuery()
  const { data, isLoading, error } = trpc.finalist.listReviewDocuments.useQuery(
    { programId: programId! },
    { enabled: !!programId, retry: false },
  )

  if (error?.data?.code === 'FORBIDDEN') {
    return (
      <Card>
        <CardContent className="flex flex-col items-center py-12 text-center">
          <ShieldAlert className="h-10 w-10 text-muted-foreground/50 mb-3" />
          <p className="font-medium">No access</p>
          <p className="text-sm text-muted-foreground">
            This review is for the Grand-Final jury and program admins.
          </p>
        </CardContent>
      </Card>
    )
  }

  // No active program resolved — nothing to review.
  if (!programLoading && !programId) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center py-12 text-center">
          <FileText className="h-10 w-10 text-muted-foreground/50 mb-3" />
          <p className="font-medium">No active program</p>
          <p className="text-sm text-muted-foreground">
            Finalist documents will appear here once a program is active.
          </p>
        </CardContent>
      </Card>
    )
  }

  if (isLoading || !data) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-64" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-brand-blue">
          Finalist Documents
        </h1>
        <p className="text-muted-foreground mt-1">
          {data.totalCount} finalist team{data.totalCount === 1 ? '' : 's'} · every file each team
          has submitted across all rounds
        </p>
      </div>
      {data.teams.map((team) => (
        <Card key={team.projectId}>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-lg">{team.teamName}</CardTitle>
            <div className="flex items-center gap-2">
              {team.category && <Badge variant="secondary">{team.category}</Badge>}
              <Badge variant="outline">
                {team.files.length} file{team.files.length === 1 ? '' : 's'}
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-2">
            {team.files.length === 0 && (
              <p className="text-sm text-muted-foreground py-4 text-center md:col-span-2">
                No files submitted.
              </p>
            )}
            {team.files.map((f) => (
              <div key={f.id} className="rounded-lg border p-3 space-y-2">
                <div className="flex items-center justify-between gap-2">
                  <span className="font-medium text-sm flex items-center gap-2 min-w-0">
                    <FileText className="h-4 w-4 shrink-0" />
                    <span className="truncate">{f.docLabel}</span>
                  </span>
                  <Button asChild variant="ghost" size="sm" className="h-7 px-2 text-xs shrink-0">
                    <a href={f.url} target="_blank" rel="noreferrer">
                      <Download className="h-3 w-3 mr-1" /> Open
                    </a>
                  </Button>
                </div>
                <div className="flex items-center gap-1.5 flex-wrap">
                  <Badge variant="outline" className="text-[10px]">
                    {f.roundLabel}
                  </Badge>
                  {f.isFinaleUpload && (
                    <Badge className="text-[10px] bg-amber-50 text-amber-700 border-amber-200">
                      Revised for finals
                    </Badge>
                  )}
                </div>
                <FilePreview
                  file={{ mimeType: f.mimeType, fileName: f.fileName }}
                  url={f.url}
                />
              </div>
            ))}
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
