import { useState, useEffect, useRef } from 'react';
import { Loader2, Music, Play, Pause, Volume2, VolumeX } from 'lucide-react';
import { formatTime } from '../file-types';
import { useSeekBar, SeekBar } from './SeekBar';

type AudioRendererProps = {
  src: string;
  fileName: string;
  autoPlay?: boolean;
};

export const AudioRenderer = ({ src, fileName, autoPlay = false }: AudioRendererProps) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [playing, setPlaying] = useState(false);
  const [currentTime, setCurrent] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);
  const [muted, setMuted] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState(false);
  const { barRef, onSeekDown } = useSeekBar(audioRef, duration);

  const ext = fileName.split('.').pop()?.toUpperCase() ?? 'AUDIO';

  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    const onLoaded = () => {
      setDuration(a.duration);
      setLoaded(true);
      if (autoPlay) {
        a.play();
        setPlaying(true);
      }
    };
    const onTime = () => setCurrent(a.currentTime);
    const onEnded = () => setPlaying(false);
    const onError = () => setError(true);
    a.addEventListener('loadedmetadata', onLoaded);
    a.addEventListener('timeupdate', onTime);
    a.addEventListener('ended', onEnded);
    a.addEventListener('error', onError);
    return () => {
      a.removeEventListener('loadedmetadata', onLoaded);
      a.removeEventListener('timeupdate', onTime);
      a.removeEventListener('ended', onEnded);
      a.removeEventListener('error', onError);
    };
  }, []);

  const togglePlay = () => {
    const a = audioRef.current;
    if (!a) return;
    if (playing) a.pause();
    else a.play();
    setPlaying(!playing);
  };

  const changeVolume = (ev: React.ChangeEvent<HTMLInputElement>) => {
    const v = parseFloat(ev.target.value);
    setVolume(v);
    setMuted(v === 0);
    if (audioRef.current) audioRef.current.volume = v;
  };

  const toggleMute = () => {
    const a = audioRef.current;
    if (!a) return;
    if (muted) {
      a.volume = volume || 1;
      setMuted(false);
    } else {
      a.volume = 0;
      setMuted(true);
    }
  };

  const pct = duration > 0 ? (currentTime / duration) * 100 : 0;

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <span className="text-sm text-red-500">Failed to load audio file</span>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-center h-full px-8">
      <audio ref={audioRef} src={src} preload="metadata" />
      <div className="w-full max-w-xl space-y-6">
        <div className="flex flex-col items-center gap-4">
          <div className="relative w-32 h-32 rounded-2xl bg-gradient-to-br from-duck-teal/20 via-duck-forest/10 to-duck-yellow/20 border-2 border-duck-dark/10 flex items-center justify-center shadow-lg">
            <Music className="h-12 w-12 text-duck-teal/60" />
            <span className="absolute bottom-2 right-2 text-[9px] font-mono font-bold text-duck-dark/30 tracking-wider">
              {ext}
            </span>
          </div>
          <div className="text-center">
            <p className="text-sm font-semibold text-duck-dark truncate max-w-xs">{fileName}</p>
            {loaded && <p className="text-xs text-duck-dark/40 mt-0.5">{formatTime(duration)}</p>}
          </div>
        </div>
        <div className="space-y-1.5">
          <SeekBar barRef={barRef} onSeekDown={onSeekDown} pct={pct} />
          <div className="flex justify-between text-[10px] font-mono text-duck-dark/40">
            <span>{formatTime(currentTime)}</span>
            <span>{formatTime(duration)}</span>
          </div>
        </div>
        <div className="flex items-center justify-center gap-6">
          <div className="flex items-center gap-2">
            <button onClick={toggleMute} className="p-1.5 text-duck-dark/40 hover:text-duck-dark transition-colors cursor-pointer">
              {muted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
            </button>
            <input
              type="range"
              min={0}
              max={1}
              step={0.01}
              value={muted ? 0 : volume}
              onChange={changeVolume}
              className="w-20 h-1 accent-duck-teal cursor-pointer"
            />
          </div>
          <button
            onClick={togglePlay}
            disabled={!loaded}
            className="w-14 h-14 rounded-full bg-duck-teal text-white flex items-center justify-center shadow-lg hover:bg-duck-teal/90 disabled:opacity-40 transition-all cursor-pointer active:scale-95"
          >
            {!loaded ? (
              <Loader2 className="h-6 w-6 animate-spin" />
            ) : playing ? (
              <Pause className="h-6 w-6" />
            ) : (
              <Play className="h-6 w-6 ml-0.5" />
            )}
          </button>
          <div className="w-[104px]" />
        </div>
      </div>
    </div>
  );
};
