import { useState, useRef, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Play, Pause, RotateCcw, Link2, Link2Off } from "lucide-react";
import { cn } from "@/lib/utils";

interface ComparisonPlayerProps {
  sourceUrl?: string;
  targetUrl?: string;
  resultUrl?: string;
  sourceDuration?: number;
  targetDuration?: number;
  resultDuration?: number;
}

export function ComparisonPlayer({
  sourceUrl,
  targetUrl,
  resultUrl,
  sourceDuration,
  targetDuration,
  resultDuration,
}: ComparisonPlayerProps) {
  const sourceRef = useRef<HTMLAudioElement>(null);
  const targetRef = useRef<HTMLAudioElement>(null);
  const resultRef = useRef<HTMLAudioElement>(null);

  const [activePlayer, setActivePlayer] = useState<"source" | "target" | "result" | null>(null);
  const [syncEnabled, setSyncEnabled] = useState(true);
  const [currentTimes, setCurrentTimes] = useState({ source: 0, target: 0, result: 0 });

  const hasAllAudio = sourceUrl && targetUrl && resultUrl;

  useEffect(() => {
    const updateTimes = () => {
      setCurrentTimes({
        source: sourceRef.current?.currentTime || 0,
        target: targetRef.current?.currentTime || 0,
        result: resultRef.current?.currentTime || 0,
      });
    };

    const interval = setInterval(updateTimes, 100);
    return () => clearInterval(interval);
  }, []);

  const handlePlay = (player: "source" | "target" | "result") => {
    const refs = { source: sourceRef, target: targetRef, result: resultRef };
    
    Object.entries(refs).forEach(([key, ref]) => {
      if (ref.current) {
        if (key === player) {
          ref.current.play();
        } else {
          ref.current.pause();
          if (syncEnabled) {
            ref.current.currentTime = refs[player].current?.currentTime || 0;
          }
        }
      }
    });

    setActivePlayer(player);
  };

  const handlePause = () => {
    [sourceRef, targetRef, resultRef].forEach((ref) => {
      if (ref.current) ref.current.pause();
    });
    setActivePlayer(null);
  };

  const handleReset = () => {
    [sourceRef, targetRef, resultRef].forEach((ref) => {
      if (ref.current) {
        ref.current.pause();
        ref.current.currentTime = 0;
      }
    });
    setActivePlayer(null);
    setCurrentTimes({ source: 0, target: 0, result: 0 });
  };

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

  const PlayerCard = ({
    type,
    url,
    audioRef,
    duration,
  }: {
    type: "source" | "target" | "result";
    url?: string;
    audioRef: React.RefObject<HTMLAudioElement>;
    duration?: number;
  }) => {
    const isActive = activePlayer === type;
    const colorClass = type === "source" ? "primary" : type === "target" ? "chart-2" : "green-500";
    const borderClass = type === "source" ? "border-primary" : type === "target" ? "border-chart-2" : "border-green-500";
    const bgClass = type === "source" ? "bg-primary/10" : type === "target" ? "bg-chart-2/10" : "bg-green-500/10";

    return (
      <div
        className={cn(
          "flex-1 p-4 rounded-lg border-2 transition-all",
          isActive ? borderClass : "border-border",
          isActive && bgClass
        )}
      >
        <audio ref={audioRef} src={url} preload="metadata" />
        
        <div className="flex items-center justify-between mb-3">
          <Badge variant="secondary" className={cn("text-xs", `text-${colorClass}`)}>
            {type.charAt(0).toUpperCase() + type.slice(1)}
          </Badge>
          <span className="text-xs font-mono text-muted-foreground">
            {formatTime(currentTimes[type])} / {formatTime(duration || 0)}
          </span>
        </div>

        <Button
          variant={isActive ? "default" : "secondary"}
          size="sm"
          className="w-full"
          onClick={() => (isActive ? handlePause() : handlePlay(type))}
          disabled={!url}
          data-testid={`button-comparison-${type}`}
        >
          {isActive ? (
            <>
              <Pause className="h-4 w-4 mr-2" />
              Pause
            </>
          ) : (
            <>
              <Play className="h-4 w-4 mr-2" />
              Play
            </>
          )}
        </Button>
      </div>
    );
  };

  if (!hasAllAudio) {
    return null;
  }

  return (
    <Card className="overflow-visible">
      <CardHeader className="flex flex-row items-center justify-between gap-2 py-4 px-6">
        <CardTitle className="text-lg">A/B Comparison</CardTitle>
        <div className="flex items-center gap-2">
          <Button
            size="icon"
            variant="ghost"
            onClick={handleReset}
            data-testid="button-comparison-reset"
          >
            <RotateCcw className="h-4 w-4" />
          </Button>
          <Button
            size="icon"
            variant={syncEnabled ? "secondary" : "ghost"}
            onClick={() => setSyncEnabled(!syncEnabled)}
            data-testid="button-sync-toggle"
          >
            {syncEnabled ? (
              <Link2 className="h-4 w-4" />
            ) : (
              <Link2Off className="h-4 w-4" />
            )}
          </Button>
        </div>
      </CardHeader>
      <CardContent className="px-6 pb-6 pt-0">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <PlayerCard
            type="source"
            url={sourceUrl}
            audioRef={sourceRef}
            duration={sourceDuration}
          />
          <PlayerCard
            type="target"
            url={targetUrl}
            audioRef={targetRef}
            duration={targetDuration}
          />
          <PlayerCard
            type="result"
            url={resultUrl}
            audioRef={resultRef}
            duration={resultDuration}
          />
        </div>

        <p className="text-xs text-muted-foreground text-center mt-4">
          {syncEnabled
            ? "Sync enabled: All players share the same position"
            : "Sync disabled: Players run independently"}
        </p>
      </CardContent>
    </Card>
  );
}
