'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Loader2, Mail, ArrowRightLeft, UserPlus, Trash2, FilePen } from 'lucide-react'
import Link from 'next/link'
import type { Route } from 'next'
import { TransferAssignmentsDialog } from './transfer-assignments-dialog'
import { InlineMemberCap } from '@/components/admin/jury/inline-member-cap'

export type JuryProgressTableMember = {
  id: string
  userId: string
  name: string
  email: string
  maxAssignmentsOverride: number | null
}

export type JuryProgressTableProps = {
  roundId: string
  members?: JuryProgressTableMember[]
  onSaveCap?: (memberId: string, val: number | null) => void
  onRemoveMember?: (memberId: string, memberName: string) => void
  onAddMember?: () => void
}

export function JuryProgressTable({
  roundId,
  members,
  onSaveCap,
  onRemoveMember,
  onAddMember,
}: JuryProgressTableProps) {
  const utils = trpc.useUtils()
  const [transferJuror, setTransferJuror] = useState<{ id: string; name: string } | null>(null)

  const { data: workload, isLoading } = trpc.analytics.getJurorWorkload.useQuery(
    { roundId },
    { refetchInterval: 15_000 },
  )

  const notifyMutation = trpc.assignment.notifySingleJurorOfAssignments.useMutation({
    onSuccess: (data) => {
      toast.success(`Notified juror of ${data.projectCount} assignment(s)`)
    },
    onError: (err) => toast.error(err.message),
  })

  const reshuffleMutation = trpc.assignment.reassignDroppedJuror.useMutation({
    onSuccess: (data) => {
      utils.assignment.listByStage.invalidate({ roundId })
      utils.roundEngine.getProjectStates.invalidate({ roundId })
      utils.analytics.getJurorWorkload.invalidate({ roundId })
      utils.roundAssignment.unassignedQueue.invalidate({ roundId })

      if (data.failedCount > 0) {
        toast.warning(`Dropped juror and reassigned ${data.movedCount} project(s). ${data.failedCount} could not be reassigned (all remaining jurors at cap/blocked).`)
      } else {
        toast.success(`Dropped juror and reassigned ${data.movedCount} project(s) evenly across available jurors.`)
      }
    },
    onError: (err) => toast.error(err.message),
  })

  const hasMembersData = members !== undefined

  return (
    <>
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-base">
              {hasMembersData ? 'Jury Members & Progress' : 'Jury Progress'}
            </CardTitle>
            <CardDescription>
              {hasMembersData
                ? 'Manage jury members, caps, and evaluation progress per juror.'
                : 'Evaluation completion per juror. Click the mail icon to notify an individual juror.'}
            </CardDescription>
          </div>
          {onAddMember && (
            <Button size="sm" onClick={onAddMember}>
              <UserPlus className="h-4 w-4 mr-1.5" />
              Add Member
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => <Skeleton key={i} className="h-10 w-full" />)}
          </div>
        ) : !workload || workload.length === 0 ? (
          hasMembersData && members && members.length > 0 ? (
            // Show members-only view when there are members but no assignments yet
            <div className="space-y-1">
              {members.map((member, idx) => (
                <MemberOnlyRow
                  key={member.id}
                  member={member}
                  idx={idx}
                  roundId={roundId}
                  onSaveCap={onSaveCap}
                  onRemoveMember={onRemoveMember}
                  notifyMutation={notifyMutation}
                />
              ))}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground text-center py-6">
              {hasMembersData ? 'No members yet. Add jury members to get started.' : 'No assignments yet'}
            </p>
          )
        ) : (
          <div className="space-y-3 max-h-[500px] overflow-y-auto overflow-x-hidden">
            {workload.map((juror) => {
              const pct = juror.completionRate
              const barGradient = pct === 100
                ? 'bg-gradient-to-r from-emerald-400 to-emerald-600'
                : pct >= 50
                  ? 'bg-gradient-to-r from-blue-400 to-blue-600'
                  : pct > 0
                    ? 'bg-gradient-to-r from-amber-400 to-amber-600'
                    : 'bg-gray-300'

              // Find the corresponding member entry for cap editing
              const member = members?.find((m) => m.userId === juror.id)

              return (
                <div key={juror.id} className="space-y-1 hover:bg-muted/20 rounded px-1 py-0.5 -mx-1 transition-colors group">
                  <div className="flex justify-between items-center text-xs">
                    <span className="font-medium truncate max-w-[140px]">{juror.name}</span>
                    <div className="flex items-center gap-2 shrink-0">
                      {member && onSaveCap && (
                        <InlineMemberCap
                          memberId={member.id}
                          currentValue={member.maxAssignmentsOverride}
                          roundId={roundId}
                          jurorUserId={member.userId}
                          onSave={(val) => onSaveCap(member.id, val)}
                        />
                      )}
                      <span className="text-muted-foreground tabular-nums">
                        {juror.completed}/{juror.assigned} ({pct}%)
                      </span>
                      <TooltipProvider delayDuration={200}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5 text-muted-foreground hover:text-foreground"
                              disabled={notifyMutation.isPending}
                              onClick={() => notifyMutation.mutate({ roundId, userId: juror.id })}
                            >
                              {notifyMutation.isPending && notifyMutation.variables?.userId === juror.id ? (
                                <Loader2 className="h-3 w-3 animate-spin" />
                              ) : (
                                <Mail className="h-3 w-3" />
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent side="left"><p>Notify this juror of their assignments</p></TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      <TooltipProvider delayDuration={200}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5 text-muted-foreground hover:text-foreground"
                              asChild
                            >
                              <Link href={`/admin/rounds/${roundId}/jurors/${juror.id}/evaluate` as Route}>
                                <FilePen className="h-3 w-3" />
                              </Link>
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent side="left"><p>Fill in evaluations on behalf of this juror</p></TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      <TooltipProvider delayDuration={200}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5 text-muted-foreground hover:text-foreground"
                              onClick={() => setTransferJuror({ id: juror.id, name: juror.name })}
                            >
                              <ArrowRightLeft className="h-3 w-3" />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent side="left"><p>Transfer assignments to other jurors</p></TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      <TooltipProvider delayDuration={200}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5 text-muted-foreground hover:text-destructive"
                              disabled={reshuffleMutation.isPending}
                              onClick={() => {
                                const ok = window.confirm(
                                  `Remove ${juror.name} from this jury pool and reassign all their unsubmitted projects to other jurors within their caps? Submitted evaluations will be preserved. This cannot be undone.`
                                )
                                if (!ok) return
                                reshuffleMutation.mutate({ roundId, jurorId: juror.id })
                              }}
                            >
                              {reshuffleMutation.isPending && reshuffleMutation.variables?.jurorId === juror.id ? (
                                <Loader2 className="h-3 w-3 animate-spin" />
                              ) : (
                                <UserPlus className="h-3 w-3" />
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent side="left"><p>Drop juror + reshuffle pending projects</p></TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      {member && onRemoveMember && (
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-5 w-5 text-destructive hover:text-destructive shrink-0"
                            >
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>Remove member?</AlertDialogTitle>
                              <AlertDialogDescription>
                                Remove {member.name} from this jury group?
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>Cancel</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => onRemoveMember(member.id, member.name)}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                              >
                                Remove
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      )}
                    </div>
                  </div>
                  <div className="h-2 bg-muted rounded-full overflow-hidden">
                    <div
                      className={cn('h-full rounded-full transition-all duration-500', barGradient)}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </CardContent>
    </Card>

    {transferJuror && (
      <TransferAssignmentsDialog
        roundId={roundId}
        sourceJuror={transferJuror}
        open={!!transferJuror}
        onClose={() => setTransferJuror(null)}
      />
    )}
    </>
  )
}

// Sub-component for member-only rows (no workload data yet)
function MemberOnlyRow({
  member,
  idx,
  roundId,
  onSaveCap,
  onRemoveMember,
  notifyMutation,
}: {
  member: JuryProgressTableMember
  idx: number
  roundId: string
  onSaveCap?: (memberId: string, val: number | null) => void
  onRemoveMember?: (memberId: string, memberName: string) => void
  notifyMutation: ReturnType<typeof trpc.assignment.notifySingleJurorOfAssignments.useMutation>
}) {
  return (
    <div
      className={cn(
        'flex items-center justify-between py-2 px-2 rounded-md transition-colors text-xs',
        idx % 2 === 1 && 'bg-muted/30',
      )}
    >
      <div className="min-w-0 flex-1">
        <p className="font-medium truncate">{member.name}</p>
        <p className="text-muted-foreground truncate">{member.email}</p>
      </div>
      <div className="flex items-center gap-2 shrink-0">
        {onSaveCap && (
          <InlineMemberCap
            memberId={member.id}
            currentValue={member.maxAssignmentsOverride}
            roundId={roundId}
            jurorUserId={member.userId}
            onSave={(val) => onSaveCap(member.id, val)}
          />
        )}
        <TooltipProvider delayDuration={200}>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 text-muted-foreground hover:text-foreground"
                disabled={notifyMutation.isPending}
                onClick={() => notifyMutation.mutate({ roundId, userId: member.userId })}
              >
                {notifyMutation.isPending && notifyMutation.variables?.userId === member.userId ? (
                  <Loader2 className="h-3 w-3 animate-spin" />
                ) : (
                  <Mail className="h-3 w-3" />
                )}
              </Button>
            </TooltipTrigger>
            <TooltipContent side="left"><p>Notify juror of assignments</p></TooltipContent>
          </Tooltip>
        </TooltipProvider>

        {onRemoveMember && (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 text-destructive hover:text-destructive shrink-0"
              >
                <Trash2 className="h-3 w-3" />
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Remove member?</AlertDialogTitle>
                <AlertDialogDescription>
                  Remove {member.name} from this jury group?
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() => onRemoveMember(member.id, member.name)}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Remove
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        )}
      </div>
    </div>
  )
}
