'use client'

import { use, useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { LiveVotingForm } from '@/components/jury/live-voting-form'
import { toast } from 'sonner'

export default function JuryLivePage({ params: paramsPromise }: { params: Promise<{ roundId: string }> }) {
  const params = use(paramsPromise)
  const utils = trpc.useUtils()
  const [notes, setNotes] = useState('')
  const [priorDataOpen, setPriorDataOpen] = useState(false)

  const { data: cursor } = trpc.live.getCursor.useQuery({ roundId: params.roundId })

  // Fetch live voting session data
  const { data: sessionData } = trpc.liveVoting.getSessionForVoting.useQuery(
    { sessionId: params.roundId },
    { enabled: !!params.roundId, refetchInterval: 2000 }
  )

  // Placeholder for prior data - this would need to be implemented in evaluation router
  const priorData = null as { averageScore?: number; evaluationCount?: number; strengths?: string; weaknesses?: string } | null

  const submitVoteMutation = trpc.liveVoting.vote.useMutation({
    onSuccess: () => {
      utils.liveVoting.getSessionForVoting.invalidate()
      toast.success('Vote submitted successfully')
    },
    onError: (err: any) => {
      toast.error(err.message)
    },
  })

  const handleVoteSubmit = (vote: { score: number; criterionScores?: Record<string, number> }) => {
    const projectId = cursor?.activeProject?.id || sessionData?.currentProject?.id
    if (!projectId) return

    const sessionId = sessionData?.session?.id || params.roundId

    submitVoteMutation.mutate({
      sessionId,
      projectId,
      score: vote.score,
      criterionScores: vote.criterionScores,
    })
  }

  // Extract voting mode and criteria from session
  const votingMode = (sessionData?.session?.votingMode ?? 'simple') as 'simple' | 'criteria'
  const criteria = (sessionData?.session?.criteriaJson as Array<{
    id: string
    label: string
    description?: string
    scale: number
    weight: number
  }> | undefined)

  const activeProject = cursor?.activeProject || sessionData?.currentProject

  if (!activeProject) {
    return (
      <div className="space-y-6">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-muted-foreground">Waiting for ceremony to begin...</p>
            <p className="mt-2 text-sm text-muted-foreground">
              The admin will control which project is displayed
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Current Project Display */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle className="text-2xl">{activeProject.title}</CardTitle>
              <CardDescription className="mt-2">
                Live project presentation
              </CardDescription>
            </div>
            {votingMode === 'criteria' && (
              <Badge variant="secondary">Criteria Voting</Badge>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {activeProject.description && (
            <p className="text-muted-foreground">{activeProject.description}</p>
          )}
        </CardContent>
      </Card>

      {/* Prior Jury Data (Collapsible) */}
      {priorData && (
        <Collapsible open={priorDataOpen} onOpenChange={setPriorDataOpen}>
          <Card>
            <CollapsibleTrigger asChild>
              <CardHeader className="cursor-pointer hover:bg-muted/50">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">Prior Evaluation Data</CardTitle>
                  {priorDataOpen ? (
                    <ChevronUp className="h-5 w-5" />
                  ) : (
                    <ChevronDown className="h-5 w-5" />
                  )}
                </div>
              </CardHeader>
            </CollapsibleTrigger>
            <CollapsibleContent>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Average Score</p>
                    <p className="mt-1 text-2xl font-bold">
                      {priorData.averageScore?.toFixed(1) || 'N/A'}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Evaluations</p>
                    <p className="mt-1 text-2xl font-bold">{priorData.evaluationCount || 0}</p>
                  </div>
                </div>
                {priorData.strengths && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Key Strengths</p>
                    <p className="mt-1 text-sm">{priorData.strengths}</p>
                  </div>
                )}
                {priorData.weaknesses && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Areas for Improvement</p>
                    <p className="mt-1 text-sm">{priorData.weaknesses}</p>
                  </div>
                )}
              </CardContent>
            </CollapsibleContent>
          </Card>
        </Collapsible>
      )}

      {/* Notes Section */}
      <Card>
        <CardHeader>
          <CardTitle>Your Notes</CardTitle>
          <CardDescription>Optional notes for this project</CardDescription>
        </CardHeader>
        <CardContent>
          <Textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Add your observations and comments..."
            rows={4}
          />
        </CardContent>
      </Card>

      {/* Voting Form */}
      <LiveVotingForm
        projectId={activeProject.id}
        votingMode={votingMode}
        criteria={criteria}
        existingVote={sessionData?.userVote ? {
          score: sessionData.userVote.score,
          criterionScoresJson: sessionData.userVote.criterionScoresJson as Record<string, number> | undefined
        } : null}
        onVoteSubmit={handleVoteSubmit}
        disabled={submitVoteMutation.isPending}
      />
    </div>
  )
}
