
"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import type { Stream } from "@/types";
import Image from "next/image";
import { Card } from "@/components/ui/card";
import { Eye, Star, Play, Pause, Volume2, VolumeX, Volume1, AlertTriangle } from "lucide-react";
import { Button } from "./ui/button";
import { Slider } from "./ui/slider";
import { cn } from "@/lib/utils";

interface AudioThumbnailCardProps {
  stream: Stream;
  isPlaying: boolean;
  onPlayToggle: (stream: Stream) => void;
}

export function AudioThumbnailCard({ stream, isPlaying, onPlayToggle }: AudioThumbnailCardProps) {
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [isInternallyPlaying, setIsInternallyPlaying] = useState(false);
  const [elapsedTime, setElapsedTime] = useState("00:00");
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [playbackError, setPlaybackError] = useState<string | null>(null);

  useEffect(() => {
    // This effect runs only once to create the audio element and attach listeners
    const audio = new Audio();
    audioRef.current = audio;
    audio.volume = volume;

    const handlePlay = () => {
      setPlaybackError(null);
      setIsInternallyPlaying(true);
    };
    const handlePause = () => setIsInternallyPlaying(false);
    const handleTimeUpdate = () => {
      if (isFinite(audio.currentTime)) {
        const minutes = Math.floor(audio.currentTime / 60);
        const seconds = Math.floor(audio.currentTime % 60);
        setElapsedTime(`${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`);
      }
    };
    const handleVolumeChange = () => {
      setVolume(audio.volume);
      setIsMuted(audio.muted);
    };
    const handleCanPlay = () => setPlaybackError(null);
    const handleError = () => {
        setPlaybackError("Could not play audio. The format may be unsupported or the source is unavailable.");
        setIsInternallyPlaying(false);
    };

    audio.addEventListener('play', handlePlay);
    audio.addEventListener('pause', handlePause);
    audio.addEventListener('timeupdate', handleTimeUpdate);
    audio.addEventListener('volumechange', handleVolumeChange);
    audio.addEventListener('canplay', handleCanPlay);
    audio.addEventListener('error', handleError);

    return () => {
      audio.pause();
      audio.removeEventListener('play', handlePlay);
      audio.removeEventListener('pause', handlePause);
      audio.removeEventListener('timeupdate', handleTimeUpdate);
      audio.removeEventListener('volumechange', handleVolumeChange);
      audio.removeEventListener('canplay', handleCanPlay);
      audio.removeEventListener('error', handleError);
      audioRef.current = null;
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    // This effect handles pausing when another stream is played
    if (!isPlaying && isInternallyPlaying) {
      audioRef.current?.pause();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isPlaying]);


  const handlePlayButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    const audio = audioRef.current;
    if (!audio) return;

    if (isInternallyPlaying) {
        audio.pause();
    } else {
        if (audio.src !== stream.sourceUrls[0]) {
          audio.src = stream.sourceUrls[0];
        }
        audio.muted = false; // Always unmute on play attempt
        const playPromise = audio.play();
        if (playPromise !== undefined) {
            playPromise.catch(error => {
                if (error.name !== 'AbortError') {
                    console.error("Playback failed:", error);
                    setPlaybackError("Could not play audio. Check browser permissions.");
                    setIsInternallyPlaying(false);
                }
            });
        }
    }
    // Notify parent about the intention to play/stop this stream
    onPlayToggle(stream);
  };

  const handleVolumeChange = (value: number[]) => {
    const newVolume = value[0];
    const audio = audioRef.current;
    if (audio) {
      audio.volume = newVolume;
      if (newVolume > 0 && audio.muted) {
        audio.muted = false;
      }
    }
  };

  const toggleMute = (e: React.MouseEvent) => {
    e.stopPropagation();
    const audio = audioRef.current;
    if (!audio) return;
    audio.muted = !audio.muted;
  };

  const VolumeIcon = isMuted || volume === 0 ? VolumeX : volume < 0.5 ? Volume1 : Volume2;
  const cardBG = isPlaying ? 'bg-accent/30' : 'bg-card';

  return (
    <div
      className="group relative h-full cursor-pointer hover:z-20"
      role="button"
      tabIndex={0}
      aria-label={`Play audio stream: ${stream.name}`}
    >
      <Card
        className={cn("h-full border-border shadow-lg transition-all duration-300 ease-in-out flex flex-col items-center justify-start p-4 overflow-hidden group-hover:scale-110", cardBG)}
      >
        {/* Top Part: Player */}
        <div className="relative w-full bg-muted rounded-lg overflow-hidden shadow-inner flex flex-col items-center justify-center p-6 h-[70%]">
            <Image
                src={`https://picsum.photos/seed/${stream.id}/300/300`}
                alt={`Background for ${stream.name}`}
                fill
                sizes="300px"
                className="object-cover"
                data-ai-hint="abstract audio"
            />
            {/* Overlay for readability */}
            <div className="absolute inset-0 bg-black/50" />
            
            <div className="relative z-10 w-full h-full flex flex-col items-center justify-center">
                {playbackError ? (
                <div className="flex flex-col items-center justify-center text-white bg-black/50 p-4 rounded-lg text-center">
                    <AlertTriangle className="w-8 h-8 mb-2 text-yellow-400" />
                    <p className="font-semibold text-base">Playback Error</p>
                    <p className="text-xs mb-3">{playbackError}</p>
                    <Button size="sm" variant="secondary" onClick={(e) => { e.stopPropagation(); handlePlayButtonClick(e); }}>Try Again</Button>
                </div>
                ) : (
                <div className="flex flex-col items-center gap-4 w-full max-w-md text-white">
                    <Button onClick={handlePlayButtonClick} size="icon" className="w-16 h-16 rounded-full bg-black/30 text-white/80 backdrop-blur-sm hover:bg-accent/80 hover:text-white">
                    {isInternallyPlaying ? <Pause className="w-8 h-8" /> : <Play className="w-8 h-8" />}
                    </Button>
                    <span className="text-2xl font-mono tracking-wider text-white/80">{elapsedTime}</span>
                    <div className="flex items-center gap-3 w-full">
                        <Button onClick={toggleMute} variant="ghost" size="icon" className="rounded-full text-white/80 hover:text-white">
                        <VolumeIcon className="w-6 h-6" />
                        </Button>
                        <Slider
                        value={[isMuted ? 0 : volume]}
                        onValueChange={handleVolumeChange}
                        max={1}
                        step={0.05}
                        className="w-full"
                        aria-label="Volume slider"
                        />
                    </div>
                </div>
                )}
            </div>
        </div>

        {/* Bottom Part: Name and Description */}
        <div className="w-full text-center flex-grow flex flex-col justify-center h-[30%] pt-4">
            <h4 className="font-semibold text-sm truncate text-foreground" title={stream.name}>{stream.name}</h4>
            {stream.description && <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{stream.description}</p>}
        </div>
      </Card>
    </div>
  );
}
