'use client';

import { use, useEffect, useState } from 'react';
import { trpc } from '@/lib/trpc/client';
import { Card, CardContent } from '@/components/ui/card';
import { AudienceVoteCard } from '@/components/public/audience-vote-card';
import { toast } from 'sonner';

export default function AudienceVotePage({ params: paramsPromise }: { params: Promise<{ roundId: string }> }) {
  const params = use(paramsPromise);
  const utils = trpc.useUtils();
  const [hasVoted, setHasVoted] = useState(false);

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

  const submitVoteMutation = trpc.liveVoting.castAudienceVote.useMutation({
    onSuccess: () => {
      setHasVoted(true);
      // Store in localStorage to prevent duplicate votes
      if (cursor?.activeProject?.id) {
        localStorage.setItem(`voted-${params.roundId}-${cursor.activeProject.id}`, 'true');
      }
      toast.success('Vote submitted! Thank you for participating.');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  // Check localStorage on mount
  useEffect(() => {
    if (cursor?.activeProject?.id) {
      const voted = localStorage.getItem(`voted-${params.roundId}-${cursor.activeProject.id}`);
      if (voted === 'true') {
        setHasVoted(true);
      }
    }
  }, [cursor?.activeProject?.id, params.roundId]);

  const handleVote = () => {
    if (!cursor?.activeProject?.id) return;

    submitVoteMutation.mutate({
      projectId: cursor.activeProject.id,
      sessionId: params.roundId,
      score: 1,
      token: `audience-${Date.now()}`
    });
  };

  if (!cursor?.activeProject) {
    return (
      <div className="container mx-auto flex min-h-screen items-center justify-center p-4">
        <Card className="w-full max-w-2xl">
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-center text-lg text-muted-foreground">
              No project is currently being presented
            </p>
            <p className="mt-2 text-center text-sm text-muted-foreground">
              Please wait for the ceremony to begin
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto flex min-h-screen items-center justify-center p-4">
      <div className="w-full">
        <div className="mb-8 text-center">
          <h1 className="text-4xl font-bold text-[#053d57]">Monaco Ocean Protection Challenge</h1>
          <p className="mt-2 text-lg text-muted-foreground">Live Audience Voting</p>
        </div>

        <AudienceVoteCard
          project={cursor.activeProject}
          onVote={handleVote}
          hasVoted={hasVoted}
        />

        <p className="mt-6 text-center text-sm text-muted-foreground">
          Live voting in progress
        </p>
      </div>
    </div>
  );
}
