'use client'

import { use, useState, useEffect } from 'react'
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 { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Progress } from '@/components/ui/progress'
import { toast } from 'sonner'
import { Clock, CheckCircle, AlertCircle, Zap } from 'lucide-react'

interface PageProps {
  params: Promise<{ sessionId: string }>
}

const SCORE_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function JuryVotingContent({ sessionId }: { sessionId: string }) {
  const [selectedScore, setSelectedScore] = useState<number | null>(null)
  const [countdown, setCountdown] = useState<number | null>(null)

  // Fetch session data with polling
  const { data, isLoading, refetch } = trpc.liveVoting.getSessionForVoting.useQuery(
    { sessionId },
    { refetchInterval: 2000 } // Poll every 2 seconds
  )

  // Vote mutation
  const vote = trpc.liveVoting.vote.useMutation({
    onSuccess: () => {
      toast.success('Vote recorded')
      refetch()
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  // Update countdown
  useEffect(() => {
    if (data?.timeRemaining !== null && data?.timeRemaining !== undefined) {
      setCountdown(data.timeRemaining)
    } else {
      setCountdown(null)
    }
  }, [data?.timeRemaining])

  // Countdown timer
  useEffect(() => {
    if (countdown === null || countdown <= 0) return

    const interval = setInterval(() => {
      setCountdown((prev) => {
        if (prev === null || prev <= 0) return 0
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(interval)
  }, [countdown])

  // Set selected score from existing vote
  useEffect(() => {
    if (data?.userVote) {
      setSelectedScore(data.userVote.score)
    } else {
      setSelectedScore(null)
    }
  }, [data?.userVote, data?.currentProject?.id])

  const handleVote = (score: number) => {
    if (!data?.currentProject) return
    setSelectedScore(score)
    vote.mutate({
      sessionId,
      projectId: data.currentProject.id,
      score,
    })
  }

  if (isLoading) {
    return <JuryVotingSkeleton />
  }

  if (!data) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-[#053d57] to-[#557f8c]">
        <Alert variant="destructive" className="max-w-md">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Session Not Found</AlertTitle>
          <AlertDescription>
            This voting session does not exist or has ended.
          </AlertDescription>
        </Alert>
      </div>
    )
  }

  const isVoting = data.session.status === 'IN_PROGRESS'
  const hasVoted = !!data.userVote

  return (
    <div className="min-h-screen flex flex-col items-center justify-center p-4 bg-gradient-to-br from-[#053d57] to-[#557f8c]">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="flex items-center justify-center gap-2 mb-2">
            <Zap className="h-6 w-6 text-primary" />
            <CardTitle>Live Voting</CardTitle>
          </div>
          <CardDescription>
            {data.round.program.name} - {data.round.name}
          </CardDescription>
        </CardHeader>

        <CardContent className="space-y-6">
          {isVoting && data.currentProject ? (
            <>
              {/* Current project */}
              <div className="text-center space-y-2">
                <Badge variant="default" className="mb-2">
                  Now Presenting
                </Badge>
                <h2 className="text-xl font-semibold">
                  {data.currentProject.title}
                </h2>
                {data.currentProject.teamName && (
                  <p className="text-muted-foreground">
                    {data.currentProject.teamName}
                  </p>
                )}
              </div>

              {/* Timer */}
              <div className="text-center">
                <div className="text-4xl font-bold text-primary mb-2">
                  {countdown !== null ? `${countdown}s` : '--'}
                </div>
                <Progress
                  value={countdown !== null ? (countdown / 30) * 100 : 0}
                  className="h-2"
                />
                <p className="text-sm text-muted-foreground mt-1">
                  Time remaining to vote
                </p>
              </div>

              {/* Score buttons */}
              <div className="space-y-2">
                <p className="text-sm font-medium text-center">Your Score</p>
                <div className="grid grid-cols-5 gap-2">
                  {SCORE_OPTIONS.map((score) => (
                    <Button
                      key={score}
                      variant={selectedScore === score ? 'default' : 'outline'}
                      size="lg"
                      className="h-14 text-xl font-bold"
                      onClick={() => handleVote(score)}
                      disabled={vote.isPending || countdown === 0}
                    >
                      {score}
                    </Button>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground text-center">
                  1 = Low, 10 = Excellent
                </p>
              </div>

              {/* Vote status */}
              {hasVoted && (
                <Alert className="bg-green-500/10 border-green-500">
                  <CheckCircle className="h-4 w-4 text-green-500" />
                  <AlertDescription>
                    Your vote has been recorded! You can change it before time runs out.
                  </AlertDescription>
                </Alert>
              )}
            </>
          ) : (
            /* Waiting state */
            <div className="text-center py-12">
              <Clock className="h-16 w-16 text-muted-foreground mx-auto mb-4 animate-pulse" />
              <h2 className="text-xl font-semibold mb-2">
                Waiting for Next Project
              </h2>
              <p className="text-muted-foreground">
                {data.session.status === 'COMPLETED'
                  ? 'The voting session has ended. Thank you for participating!'
                  : 'The admin will start voting for the next project.'}
              </p>
              {data.session.status !== 'COMPLETED' && (
                <p className="text-sm text-muted-foreground mt-4">
                  This page will update automatically.
                </p>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Mobile-friendly footer */}
      <p className="text-white/60 text-sm mt-4">
        MOPC Live Voting
      </p>
    </div>
  )
}

function JuryVotingSkeleton() {
  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-[#053d57] to-[#557f8c]">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <Skeleton className="h-6 w-32 mx-auto" />
          <Skeleton className="h-4 w-48 mx-auto mt-2" />
        </CardHeader>
        <CardContent className="space-y-6">
          <Skeleton className="h-20 w-full" />
          <Skeleton className="h-12 w-full" />
          <div className="grid grid-cols-5 gap-2">
            {[...Array(10)].map((_, i) => (
              <Skeleton key={i} className="h-14 w-full" />
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

export default function JuryLiveVotingPage({ params }: PageProps) {
  const { sessionId } = use(params)

  return <JuryVotingContent sessionId={sessionId} />
}
