'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, Pause, 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);
  const [isTimerRunning, setIsTimerRunning] = useState(false);

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

  const jumpMutation = trpc.live.jump.useMutation({
    onSuccess: () => {
      utils.live.getCursor.invalidate({ roundId });
    },
    onError: (err) => toast.error(err.message),
  });

  const pauseMutation = trpc.live.pause.useMutation({
    onSuccess: () => {
      utils.live.getCursor.invalidate({ roundId });
      toast.success('Live session paused');
    },
    onError: (err) => toast.error(err.message),
  });

  const resumeMutation = trpc.live.resume.useMutation({
    onSuccess: () => {
      utils.live.getCursor.invalidate({ roundId });
      toast.success('Live session resumed');
    },
    onError: (err) => toast.error(err.message),
  });

  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 currentIndex = cursor?.activeOrderIndex ?? 0;
  const totalProjects = cursor?.totalProjects ?? 0;
  const isNavigating = jumpMutation.isPending;

  const handlePrevious = () => {
    if (currentIndex <= 0) {
      toast.info('Already at the first project');
      return;
    }
    jumpMutation.mutate({ roundId, index: currentIndex - 1 });
  };

  const handleNext = () => {
    if (currentIndex >= totalProjects - 1) {
      toast.info('Already at the last project');
      return;
    }
    jumpMutation.mutate({ roundId, index: currentIndex + 1 });
  };

  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 items-center gap-2">
              {cursor && (
                <span className="text-sm text-muted-foreground tabular-nums">
                  {currentIndex + 1} / {totalProjects}
                </span>
              )}
              <Button
                variant="outline"
                size="icon"
                onClick={handlePrevious}
                disabled={isNavigating || currentIndex <= 0}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="icon"
                onClick={handleNext}
                disabled={isNavigating || currentIndex >= totalProjects - 1}
              >
                <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>
                {cursor.activeProject.teamName && (
                  <p className="text-muted-foreground">{cursor.activeProject.teamName}</p>
                )}
              </div>
              {cursor.activeProject.tags && (cursor.activeProject.tags as string[]).length > 0 && (
                <div className="flex flex-wrap gap-1">
                  {(cursor.activeProject.tags as string[]).map((tag: string) => (
                    <Badge key={tag} variant="secondary" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <p className="text-muted-foreground">
              {cursor ? 'No project selected' : 'No live session active for this round'}
            </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>

      {/* Session Controls */}
      <Card>
        <CardHeader>
          <CardTitle>Session Controls</CardTitle>
          <CardDescription>Pause or resume the live presentation</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {cursor?.isPaused ? (
            <Button
              className="w-full"
              onClick={() => resumeMutation.mutate({ roundId })}
              disabled={resumeMutation.isPending}
            >
              <Play className="mr-2 h-4 w-4" />
              {resumeMutation.isPending ? 'Resuming...' : 'Resume Session'}
            </Button>
          ) : (
            <Button
              className="w-full"
              variant="outline"
              onClick={() => pauseMutation.mutate({ roundId })}
              disabled={pauseMutation.isPending || !cursor}
            >
              <Pause className="mr-2 h-4 w-4" />
              {pauseMutation.isPending ? 'Pausing...' : 'Pause Session'}
            </Button>
          )}
          {cursor?.isPaused && (
            <Badge variant="destructive" className="w-full justify-center py-1">
              Session Paused
            </Badge>
          )}
          {cursor?.openCohorts && cursor.openCohorts.length > 0 && (
            <div className="rounded-lg border p-3">
              <p className="text-sm font-medium mb-2">Open Voting Windows</p>
              {cursor.openCohorts.map((cohort: any) => (
                <div key={cohort.id} className="flex items-center justify-between text-sm">
                  <span>{cohort.name}</span>
                  <Badge variant="outline">{cohort.votingMode}</Badge>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
