'use client'

import { use, useState, useEffect, useRef, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { MultiWindowDocViewer } from '@/components/jury/multi-window-doc-viewer'
import { ArrowLeft, Save, Send, UserCheck, Lock } from 'lucide-react'
import { toast } from 'sonner'
import type { EvaluationConfig } from '@/types/competition-configs'
import {
  EvaluationFormFields,
  parseCriteriaFromForm,
} from '@/components/evaluation/evaluation-form-fields'

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

export default function AdminProxyEvaluatePage({ params: paramsPromise }: PageProps) {
  const { roundId, userId, projectId } = use(paramsPromise)
  const router = useRouter()
  const utils = trpc.useUtils()
  const backHref = `/admin/rounds/${roundId}/jurors/${userId}/evaluate` as Route

  // Form state — mirrors the juror evaluate page
  const [criteriaValues, setCriteriaValues] = useState<Record<string, number | boolean | string>>({})
  const [globalScore, setGlobalScore] = useState('')
  const [binaryDecision, setBinaryDecision] = useState<'' | 'accept' | 'reject'>('')
  const [feedbackText, setFeedbackText] = useState('')

  const isDirtyRef = useRef(false)
  const evaluationIdRef = useRef<string | null>(null)
  const isSubmittedRef = useRef(false)
  const isSubmittingRef = useRef(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const startPromiseRef = useRef<Promise<{ id: string }> | null>(null)
  const autosaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null)
  const [confirmOpen, setConfirmOpen] = useState(false)

  // Juror + round + all assignments (we filter to the one matching projectId)
  const { data: jurorData, isLoading: jurorLoading } =
    trpc.evaluation.getJurorAssignmentsForRound.useQuery({ roundId, userId })

  const assignment = jurorData?.assignments.find((a) => a.project.id === projectId)
  const project = assignment?.project
  const round = jurorData?.round
  const juror = jurorData?.juror

  // Full round config (for scoringMode / requireFeedback etc.)
  const { data: fullRound } = trpc.round.getById.useQuery(
    { id: roundId },
    { enabled: !!roundId },
  )

  // Existing evaluation for this assignment, if any (admin-readable via evaluation.get)
  const { data: existingEvaluation } = trpc.evaluation.get.useQuery(
    { assignmentId: assignment?.id ?? '' },
    { enabled: !!assignment?.id },
  )

  // Active form for this category
  const { data: activeForm } = trpc.evaluation.getStageForm.useQuery(
    { roundId, category: project?.competitionCategory },
    { enabled: !!roundId && !!project },
  )

  const startMutation = trpc.evaluation.adminStart.useMutation()
  const autosaveMutation = trpc.evaluation.adminAutosave.useMutation({
    onSuccess: () => {
      isDirtyRef.current = false
      setLastSavedAt(new Date())
    },
  })
  const submitMutation = trpc.evaluation.adminSubmitOnBehalf.useMutation({
    onSuccess: () => {
      isSubmittedRef.current = true
      isDirtyRef.current = false
      utils.evaluation.getJurorAssignmentsForRound.invalidate({ roundId, userId })
      utils.evaluation.get.invalidate()
      utils.analytics.getJurorWorkload.invalidate({ roundId })
      toast.success(`Evaluation submitted on behalf of ${juror?.name || 'juror'}`)
      router.push(backHref)
    },
    onError: (err) => {
      toast.error(err.message)
      isSubmittingRef.current = false
      setIsSubmitting(false)
    },
  })

  useEffect(() => {
    if (existingEvaluation?.id) {
      evaluationIdRef.current = existingEvaluation.id
    }
  }, [existingEvaluation?.id])

  // Load existing evaluation values (draft or submitted)
  useEffect(() => {
    if (existingEvaluation) {
      if (existingEvaluation.criterionScoresJson) {
        const values: Record<string, number | boolean | string> = {}
        Object.entries(existingEvaluation.criterionScoresJson).forEach(([key, value]) => {
          if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') {
            values[key] = value
          }
        })
        setCriteriaValues(values)
      }
      if (existingEvaluation.globalScore != null) {
        setGlobalScore(existingEvaluation.globalScore.toString())
      }
      if (existingEvaluation.binaryDecision !== null) {
        setBinaryDecision(existingEvaluation.binaryDecision ? 'accept' : 'reject')
      }
      if (existingEvaluation.feedbackText) {
        setFeedbackText(existingEvaluation.feedbackText)
      }
      isDirtyRef.current = false
    }
  }, [existingEvaluation])

  // Config
  const evalConfig: EvaluationConfig | null = (fullRound?.configJson as EvaluationConfig | null) ?? null
  const scoringMode = evalConfig?.scoringMode ?? 'criteria'
  const requireFeedback = evalConfig?.requireFeedback ?? true
  const feedbackMinLength = evalConfig?.feedbackMinLength ?? 10

  const criteria = parseCriteriaFromForm(
    activeForm?.criteriaJson as ReadonlyArray<Record<string, unknown>> | null | undefined,
  )

  // Seed midpoint values for numeric criteria on first load
  const criteriaInitializedRef = useRef(false)
  useEffect(() => {
    if (criteriaInitializedRef.current || criteria.length === 0) return
    if (existingEvaluation?.criterionScoresJson) return
    criteriaInitializedRef.current = true

    const defaults: Record<string, number | boolean | string> = {}
    for (const c of criteria) {
      if (c.type === 'numeric') {
        defaults[c.id] = Math.ceil((c.minScore + c.maxScore) / 2)
      }
    }
    if (Object.keys(defaults).length > 0) {
      setCriteriaValues((prev) => ({ ...defaults, ...prev }))
    }
  }, [criteria, existingEvaluation?.criterionScoresJson])

  const buildSavePayload = useCallback(() => {
    return {
      criterionScoresJson: scoringMode === 'criteria' ? criteriaValues : undefined,
      globalScore: scoringMode === 'global' && globalScore ? parseInt(globalScore, 10) : null,
      binaryDecision: scoringMode === 'binary' && binaryDecision ? binaryDecision === 'accept' : null,
      feedbackText: feedbackText || null,
    }
  }, [scoringMode, criteriaValues, globalScore, binaryDecision, feedbackText])

  const performAutosave = useCallback(async () => {
    if (!isDirtyRef.current || isSubmittedRef.current || isSubmittingRef.current) return
    if (existingEvaluation?.status === 'SUBMITTED' || existingEvaluation?.status === 'LOCKED') return

    let evalId = evaluationIdRef.current
    if (!evalId && assignment) {
      try {
        if (!startPromiseRef.current) {
          startPromiseRef.current = startMutation.mutateAsync({ assignmentId: assignment.id })
        }
        const newEval = await startPromiseRef.current
        evalId = newEval.id
        evaluationIdRef.current = evalId
      } catch {
        return
      } finally {
        startPromiseRef.current = null
      }
    }
    if (!evalId) return

    autosaveMutation.mutate({ id: evalId, ...buildSavePayload() })
  }, [assignment, existingEvaluation?.status, startMutation, autosaveMutation, buildSavePayload])

  // Debounced autosave
  useEffect(() => {
    if (!isDirtyRef.current) return
    if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current)
    autosaveTimerRef.current = setTimeout(() => {
      performAutosave()
    }, 3000)
    return () => {
      if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current)
    }
  }, [criteriaValues, globalScore, binaryDecision, feedbackText, performAutosave])

  // Save on unmount
  useEffect(() => {
    return () => {
      if (isDirtyRef.current && !isSubmittedRef.current && evaluationIdRef.current) {
        performAutosave()
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const handleCriterionChange = (key: string, value: number | boolean | string) => {
    setCriteriaValues((prev) => ({ ...prev, [key]: value }))
    isDirtyRef.current = true
  }
  const handleGlobalScoreChange = (value: string) => {
    setGlobalScore(value)
    isDirtyRef.current = true
  }
  const handleBinaryChange = (value: 'accept' | 'reject') => {
    setBinaryDecision(value)
    isDirtyRef.current = true
  }
  const handleFeedbackChange = (value: string) => {
    setFeedbackText(value)
    isDirtyRef.current = true
  }

  const handleSaveDraft = async () => {
    if (!assignment) {
      toast.error('Assignment not found')
      return
    }
    let evaluationId = evaluationIdRef.current
    if (!evaluationId) {
      if (!startPromiseRef.current) {
        startPromiseRef.current = startMutation.mutateAsync({ assignmentId: assignment.id })
      }
      const newEval = await startPromiseRef.current
      startPromiseRef.current = null
      evaluationId = newEval.id
      evaluationIdRef.current = evaluationId
    }
    autosaveMutation.mutate(
      { id: evaluationId, ...buildSavePayload() },
      {
        onSuccess: () => {
          isDirtyRef.current = false
          setLastSavedAt(new Date())
          toast.success('Draft saved', { duration: 1500 })
        },
      },
    )
  }

  const validateBeforeSubmit = (): string | null => {
    if (scoringMode === 'criteria') {
      const requiredCriteria = criteria.filter((c) => c.type !== 'section_header' && c.required)
      for (const c of requiredCriteria) {
        const val = criteriaValues[c.id]
        if (c.type === 'numeric' && (val === undefined || val === null)) return `Please score "${c.label}"`
        if ((c.type === 'boolean' || c.type === 'advance') && val === undefined) return `Please answer "${c.label}"`
        if (c.type === 'text' && (!val || (typeof val === 'string' && !val.trim()))) return `Please fill in "${c.label}"`
      }
    }
    if (scoringMode === 'global') {
      const score = parseInt(globalScore, 10)
      if (isNaN(score) || score < 1 || score > 10) return 'Please enter a valid score between 1 and 10'
    }
    if (scoringMode === 'binary') {
      if (!binaryDecision) return 'Please select accept or reject'
    }
    if (requireFeedback) {
      if (!feedbackText.trim() || feedbackText.length < feedbackMinLength) {
        return `Please provide feedback (minimum ${feedbackMinLength} characters)`
      }
    }
    return null
  }

  const handleOpenConfirm = () => {
    const error = validateBeforeSubmit()
    if (error) {
      toast.error(error)
      return
    }
    setConfirmOpen(true)
  }

  const handleConfirmedSubmit = async () => {
    if (autosaveTimerRef.current) {
      clearTimeout(autosaveTimerRef.current)
      autosaveTimerRef.current = null
    }
    if (!assignment) {
      toast.error('Assignment not found')
      return
    }
    isSubmittingRef.current = true
    setIsSubmitting(true)

    let evaluationId = evaluationIdRef.current
    if (!evaluationId) {
      if (!startPromiseRef.current) {
        startPromiseRef.current = startMutation.mutateAsync({ assignmentId: assignment.id })
      }
      const newEval = await startPromiseRef.current
      startPromiseRef.current = null
      evaluationId = newEval.id
      evaluationIdRef.current = evaluationId
    }

    // Compute global score from weighted criteria (same as juror page)
    const numericCriteria = criteria.filter((c) => c.type === 'numeric')
    let computedGlobalScore = 5
    if (scoringMode === 'criteria' && numericCriteria.length > 0) {
      let totalWeight = 0
      let weightedSum = 0
      for (const c of numericCriteria) {
        const val = criteriaValues[c.id]
        if (typeof val === 'number') {
          const w = c.weight ?? 1
          const normalized = ((val - c.minScore) / (c.maxScore - c.minScore)) * 9 + 1
          weightedSum += normalized * w
          totalWeight += w
        }
      }
      if (totalWeight > 0) {
        computedGlobalScore = Math.round(weightedSum / totalWeight)
      }
    }

    submitMutation.mutate({
      id: evaluationId,
      criterionScoresJson: scoringMode === 'criteria' ? criteriaValues : {},
      globalScore: scoringMode === 'global' ? parseInt(globalScore, 10) : computedGlobalScore,
      binaryDecision: scoringMode === 'binary' ? binaryDecision === 'accept' : true,
      feedbackText: feedbackText || 'No feedback provided',
    })
  }

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

  if (!assignment || !project) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" size="sm" asChild>
          <Link href={backHref}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Assignments
          </Link>
        </Button>
        <Card className="border-l-4 border-l-red-500">
          <CardContent className="p-6">
            <p className="font-semibold">Assignment not found</p>
            <p className="text-sm text-muted-foreground mt-1">
              This juror does not have an assignment for this project in the selected round.
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isSubmittedEvaluation = existingEvaluation?.status === 'SUBMITTED' || existingEvaluation?.status === 'LOCKED'
  const isReadOnly = isSubmittedEvaluation
  const hasCOI = assignment.conflictOfInterest?.hasConflict === true

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href={backHref}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Assignments
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-brand-blue">
            {isReadOnly ? 'Submitted Evaluation' : 'Fill In Evaluation'}
          </h1>
          <div className="flex items-center gap-2 mt-1 flex-wrap">
            <p className="text-muted-foreground">{project.title}</p>
            {project.competitionCategory && (
              <Badge
                variant="secondary"
                className={
                  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>
            )}
          </div>
        </div>
      </div>

      <Card className="border-l-4 border-l-amber-500 bg-amber-50/40">
        <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">
              Acting on behalf of {juror.name || juror.email}
            </p>
            <p className="text-muted-foreground mt-1">
              Window and round-active checks are bypassed for this submission. A proxy audit entry
              is recorded with your admin ID and the juror&apos;s ID.
            </p>
          </div>
        </CardContent>
      </Card>

      {isReadOnly && (
        <Card className="border-l-4 border-l-blue-500 bg-blue-50/50">
          <CardContent className="flex items-start gap-3 p-4">
            <Lock className="h-5 w-5 text-blue-600 shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="font-medium text-sm">View-Only</p>
              <p className="text-sm text-muted-foreground mt-1">
                This evaluation has already been submitted. To change it, reset via the
                round dashboard first.
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {hasCOI && !isReadOnly && (
        <Card className="border-l-4 border-l-red-500 bg-red-50/40">
          <CardContent className="flex items-start gap-3 p-4">
            <Lock className="h-5 w-5 text-red-600 shrink-0 mt-0.5" />
            <div className="flex-1 text-sm">
              <p className="font-medium">Conflict of interest declared</p>
              <p className="text-muted-foreground mt-1">
                The juror declared a conflict on this project. Reassign via the COI review
                workflow instead of submitting a proxy evaluation.
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      <MultiWindowDocViewer roundId={roundId} projectId={projectId} />

      <EvaluationFormFields
        criteria={criteria}
        scoringMode={scoringMode}
        requireFeedback={requireFeedback}
        feedbackMinLength={feedbackMinLength}
        criteriaValues={criteriaValues}
        globalScore={globalScore}
        binaryDecision={binaryDecision}
        feedbackText={feedbackText}
        isReadOnly={isReadOnly || hasCOI}
        lastSavedAt={lastSavedAt}
        onCriterionChange={handleCriterionChange}
        onGlobalScoreChange={handleGlobalScoreChange}
        onBinaryChange={handleBinaryChange}
        onFeedbackChange={handleFeedbackChange}
      />

      {isReadOnly ? (
        <div className="flex items-center">
          <Button variant="outline" asChild>
            <Link href={backHref}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back
            </Link>
          </Button>
        </div>
      ) : (
        <div className="flex items-center justify-between flex-wrap gap-4">
          <Button variant="outline" asChild>
            <Link href={backHref}>Cancel</Link>
          </Button>
          <div className="flex gap-3">
            <Button
              variant="outline"
              onClick={handleSaveDraft}
              disabled={autosaveMutation.isPending || submitMutation.isPending || hasCOI}
            >
              <Save className="mr-2 h-4 w-4" />
              {autosaveMutation.isPending ? 'Saving...' : 'Save Draft'}
            </Button>
            <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
              <AlertDialogTrigger asChild>
                <Button
                  onClick={handleOpenConfirm}
                  disabled={submitMutation.isPending || isSubmitting || hasCOI}
                  className="bg-brand-blue hover:bg-brand-blue-light"
                >
                  <Send className="mr-2 h-4 w-4" />
                  {submitMutation.isPending ? 'Submitting...' : 'Submit on behalf'}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Submit on behalf of {juror.name || juror.email}?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This will submit the evaluation as if it came from the juror. The current
                    voting window and round-active status will be bypassed. The audit log will
                    record both your admin ID and the juror&apos;s ID. This action cannot be
                    undone without resetting the evaluation first.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel disabled={isSubmitting}>Cancel</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={handleConfirmedSubmit}
                    disabled={isSubmitting}
                    className="bg-brand-blue hover:bg-brand-blue-light"
                  >
                    {isSubmitting ? 'Submitting...' : 'Yes, submit'}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        </div>
      )}
    </div>
  )
}
