'use client';

import { useState, useEffect } from 'react';
import { trpc } from '@/lib/trpc/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ChevronLeft, ChevronRight, Play, Square, Timer } from 'lucide-react';
import { toast } from 'sonner';

interface LiveControlPanelProps {
  roundId: string;
  competitionId: string;
}

export function LiveControlPanel({ roundId, competitionId }: LiveControlPanelProps) {
  const utils = trpc.useUtils();
  const [timerSeconds, setTimerSeconds] = useState(300); // 5 minutes default
  const [isTimerRunning, setIsTimerRunning] = useState(false);

  const { data: cursor } = trpc.live.getCursor.useQuery({ roundId });
  // TODO: Add getScores to live router
  const scores: any[] = [];

  // TODO: Implement cursor mutation
  const moveCursorMutation = {
    mutate: () => {},
    isPending: false
  };

  useEffect(() => {
    if (!isTimerRunning) return;

    const interval = setInterval(() => {
      setTimerSeconds((prev) => {
        if (prev <= 1) {
          setIsTimerRunning(false);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [isTimerRunning]);

  const handlePrevious = () => {
    // TODO: Implement previous navigation
    toast.info('Previous navigation not yet implemented');
  };

  const handleNext = () => {
    // TODO: Implement next navigation
    toast.info('Next navigation not yet implemented');
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className="space-y-6">
      {/* Current Project Card */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Current Project</CardTitle>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={handlePrevious}
                disabled={moveCursorMutation.isPending}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="icon"
                onClick={handleNext}
                disabled={moveCursorMutation.isPending}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {cursor?.activeProject ? (
            <div className="space-y-4">
              <div>
                <h3 className="text-2xl font-bold">{cursor.activeProject.title}</h3>
              </div>
              <div className="text-sm text-muted-foreground">
                Total projects: {cursor.totalProjects}
              </div>
            </div>
          ) : (
            <p className="text-muted-foreground">No project selected</p>
          )}
        </CardContent>
      </Card>

      {/* Timer Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Timer className="h-5 w-5" />
            Timer
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="text-center">
            <div className="text-5xl font-bold tabular-nums">{formatTime(timerSeconds)}</div>
          </div>
          <div className="flex flex-col gap-2 sm:flex-row">
            {!isTimerRunning ? (
              <Button
                className="flex-1"
                onClick={() => setIsTimerRunning(true)}
                disabled={timerSeconds === 0}
              >
                <Play className="mr-2 h-4 w-4" />
                Start Timer
              </Button>
            ) : (
              <Button className="flex-1" onClick={() => setIsTimerRunning(false)} variant="destructive">
                <Square className="mr-2 h-4 w-4" />
                Stop Timer
              </Button>
            )}
            <Button
              variant="outline"
              onClick={() => {
                setTimerSeconds(300);
                setIsTimerRunning(false);
              }}
            >
              Reset (5:00)
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Voting Controls */}
      <Card>
        <CardHeader>
          <CardTitle>Voting Controls</CardTitle>
          <CardDescription>Manage jury and audience voting</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <Button className="w-full" variant="default">
            <Play className="mr-2 h-4 w-4" />
            Open Jury Voting
          </Button>
          <Button className="w-full" variant="outline">
            Close Voting
          </Button>
        </CardContent>
      </Card>

      {/* Scores Display */}
      <Card>
        <CardHeader>
          <CardTitle>Live Scores</CardTitle>
        </CardHeader>
        <CardContent>
          {scores && scores.length > 0 ? (
            <div className="space-y-2">
              {scores.map((score: any, index: number) => (
                <div
                  key={score.projectId}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div>
                    <p className="font-medium">
                      #{index + 1} {score.projectTitle}
                    </p>
                    <p className="text-sm text-muted-foreground">{score.votes} votes</p>
                  </div>
                  <Badge variant="outline">{score.totalScore.toFixed(1)}</Badge>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-muted-foreground">No scores yet</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
