'use client'

import { use } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import {
  ArrowLeft,
  ArrowRight,
  CheckCircle2,
  Clock,
  Pencil,
  ShieldAlert,
  UserCheck,
} from 'lucide-react'
import { cn } from '@/lib/utils'

type PageProps = {
  params: Promise<{ roundId: string; userId: string }>
}

export default function AdminJurorProxyEvaluatePage({ params: paramsPromise }: PageProps) {
  const { roundId, userId } = use(paramsPromise)

  const { data, isLoading } = trpc.evaluation.getJurorAssignmentsForRound.useQuery({
    roundId,
    userId,
  })

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

  const { juror, round, assignments } = data
  const pending = assignments.filter((a) => a.evaluation?.status !== 'SUBMITTED' && a.evaluation?.status !== 'LOCKED')
  const completed = assignments.filter((a) => a.evaluation?.status === 'SUBMITTED' || a.evaluation?.status === 'LOCKED')

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/admin/rounds/${roundId}` as Route}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Round
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-brand-blue">
            Proxy Evaluations
          </h1>
          <p className="text-muted-foreground mt-1">
            Filling in on behalf of <span className="font-semibold">{juror.name || juror.email}</span>{' '}
            &middot; {round.name}
          </p>
        </div>
      </div>

      <Card className="border-l-4 border-l-amber-500">
        <CardContent className="flex items-start gap-3 p-4">
          <UserCheck className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
          <div className="flex-1 text-sm">
            <p className="font-medium">You are acting on behalf of a juror</p>
            <p className="text-muted-foreground mt-1">
              Each submission is recorded in the audit log with your admin ID and the juror&apos;s
              ID. Voting-window and round-active checks are bypassed for proxy submissions, but
              COI-declared projects cannot be proxy-submitted.
            </p>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-base">Pending assignments</CardTitle>
              <CardDescription>
                {pending.length === 0
                  ? 'No pending evaluations — this juror has completed everything assigned to them.'
                  : `${pending.length} project${pending.length === 1 ? '' : 's'} awaiting evaluation.`}
              </CardDescription>
            </div>
            <Badge variant="secondary" className="shrink-0">
              {completed.length}/{assignments.length} complete
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="space-y-2">
          {pending.length === 0 ? (
            <p className="text-sm text-muted-foreground py-4 text-center">Nothing to do here.</p>
          ) : (
            pending.map((a) => (
              <AssignmentRow
                key={a.id}
                roundId={roundId}
                userId={userId}
                assignment={a}
                mode="pending"
              />
            ))
          )}
        </CardContent>
      </Card>

      {completed.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Completed assignments</CardTitle>
            <CardDescription>
              Already submitted. Click to view (read-only).
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            {completed.map((a) => (
              <AssignmentRow
                key={a.id}
                roundId={roundId}
                userId={userId}
                assignment={a}
                mode="completed"
              />
            ))}
          </CardContent>
        </Card>
      )}
    </div>
  )
}

type AssignmentRowProps = {
  roundId: string
  userId: string
  assignment: {
    id: string
    isCompleted: boolean
    project: {
      id: string
      title: string
      competitionCategory: 'STARTUP' | 'BUSINESS_CONCEPT' | null
      teamName: string | null
    }
    evaluation: {
      id: string
      status: 'NOT_STARTED' | 'DRAFT' | 'SUBMITTED' | 'LOCKED'
      globalScore: number | null
      binaryDecision: boolean | null
      submittedAt: Date | null
    } | null
    conflictOfInterest: { id: string; hasConflict: boolean } | null
  }
  mode: 'pending' | 'completed'
}

function AssignmentRow({ roundId, userId, assignment, mode }: AssignmentRowProps) {
  const { project, evaluation, conflictOfInterest } = assignment
  const hasCOI = conflictOfInterest?.hasConflict === true

  const statusLabel = evaluation?.status === 'SUBMITTED'
    ? 'Submitted'
    : evaluation?.status === 'DRAFT'
      ? 'Draft in progress'
      : evaluation?.status === 'LOCKED'
        ? 'Locked'
        : 'Not started'

  const statusColor =
    evaluation?.status === 'SUBMITTED' || evaluation?.status === 'LOCKED'
      ? 'text-emerald-600'
      : evaluation?.status === 'DRAFT'
        ? 'text-amber-600'
        : 'text-muted-foreground'

  const StatusIcon =
    evaluation?.status === 'SUBMITTED' || evaluation?.status === 'LOCKED'
      ? CheckCircle2
      : evaluation?.status === 'DRAFT'
        ? Pencil
        : Clock

  const href = `/admin/rounds/${roundId}/jurors/${userId}/evaluate/${project.id}` as Route

  return (
    <div
      className={cn(
        'flex items-center justify-between gap-3 p-3 rounded-lg border transition-colors',
        mode === 'pending' ? 'hover:bg-muted/30' : 'bg-muted/20',
      )}
    >
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-2 flex-wrap">
          <p className="font-medium text-sm truncate">{project.title}</p>
          {project.competitionCategory && (
            <Badge
              variant="secondary"
              className={cn(
                'shrink-0',
                project.competitionCategory === 'STARTUP'
                  ? 'bg-violet-100 text-violet-700 border-violet-200'
                  : 'bg-sky-100 text-sky-700 border-sky-200',
              )}
            >
              {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
            </Badge>
          )}
          {hasCOI && (
            <Badge variant="destructive" className="shrink-0 gap-1">
              <ShieldAlert className="h-3 w-3" />
              COI declared
            </Badge>
          )}
        </div>
        <div className={cn('flex items-center gap-1.5 text-xs mt-1', statusColor)}>
          <StatusIcon className="h-3.5 w-3.5" />
          <span>{statusLabel}</span>
          {evaluation?.status === 'SUBMITTED' && evaluation.globalScore !== null && (
            <span className="ml-2 text-muted-foreground">Score: {evaluation.globalScore}/10</span>
          )}
          {project.teamName && (
            <span className="ml-2 text-muted-foreground">&middot; {project.teamName}</span>
          )}
        </div>
      </div>
      <Button size="sm" variant={mode === 'pending' ? 'default' : 'outline'} asChild disabled={hasCOI}>
        <Link href={href} aria-disabled={hasCOI} className={hasCOI ? 'pointer-events-none opacity-50' : ''}>
          {mode === 'pending' ? 'Fill in' : 'View'}
          <ArrowRight className="ml-1.5 h-3.5 w-3.5" />
        </Link>
      </Button>
    </div>
  )
}
