'use client'

import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { toast } from 'sonner'
import { Eye } from 'lucide-react'

/**
 * Admin picker: which previously-submitted documents finale judges see on the
 * review page. Default (switch off) shows everything; switching to curated
 * mode starts with all slots ticked, and the admin unticks what to hide.
 * Grand Final round uploads are always visible regardless.
 */
export function ReviewDocsPicker({ programId, roundId }: { programId: string; roundId: string }) {
  const utils = trpc.useUtils()
  const { data } = trpc.finalist.getReviewDocSettings.useQuery({ programId, roundId })
  const set = trpc.finalist.setReviewVisibleRequirements.useMutation({
    onSuccess: () => utils.finalist.getReviewDocSettings.invalidate({ programId, roundId }),
    onError: (e) => toast.error(e.message),
  })
  if (!data || data.options.length === 0) return null

  const curated = data.selectedIds !== null
  const selected = new Set(data.selectedIds ?? data.options.map((o) => o.requirementId))
  const toggleSlot = (id: string, on: boolean) => {
    const next = new Set(selected)
    if (on) next.add(id)
    else next.delete(id)
    set.mutate({ roundId, requirementIds: [...next] })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-lg">
          <Eye className="h-5 w-5" /> Documents shown to judges
        </CardTitle>
        <CardDescription>
          Choose which previously submitted documents judges see on the finalist review page.
          Documents uploaded directly to this Grand Final round are always visible.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="flex items-center gap-2">
          <Switch
            id="curate-review-docs"
            checked={curated}
            disabled={set.isPending}
            onCheckedChange={(v) =>
              set.mutate({ roundId, requirementIds: v ? data.options.map((o) => o.requirementId) : null })}
          />
          <Label htmlFor="curate-review-docs" className="text-sm text-muted-foreground cursor-pointer">
            {curated ? 'Curated — judges see only the checked documents' : 'Showing all submitted documents'}
          </Label>
        </div>
        {curated && (
          <div className="space-y-2">
            {data.options.map((o) => (
              <label key={o.requirementId} className="flex items-center gap-2 text-sm cursor-pointer">
                <Checkbox
                  checked={selected.has(o.requirementId)}
                  disabled={set.isPending}
                  onCheckedChange={(v) => toggleSlot(o.requirementId, v === true)}
                />
                <span>{o.name} — {o.roundName}</span>
                <span className="text-xs text-muted-foreground">
                  ({o.fileCount} file{o.fileCount === 1 ? '' : 's'})
                </span>
              </label>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
