"use client";

import React, { useEffect, useRef, useState } from "react";
import Hls from "hls.js";

interface LiveHlsPlayerProps {
  streamUrl?: string;
  poster?: string;
  isMuted: boolean;
  className?: string;
  onPlaying?: () => void;
  onError?: () => void;
}

export function LiveHlsPlayer({
  streamUrl,
  poster,
  isMuted,
  className = "w-full h-full object-cover",
  onPlaying,
  onError,
}: LiveHlsPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const hlsRef = useRef<Hls | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    setHasError(false);
    setIsPlaying(false);

    if (hlsRef.current) {
      hlsRef.current.destroy();
      hlsRef.current = null;
    }

    if (!streamUrl || !streamUrl.includes(".m3u8")) {
      setHasError(true);
      return;
    }

    if (typeof window !== "undefined" && Hls.isSupported()) {
      const hls = new Hls({
        enableWorker: true,
        lowLatencyMode: true,
        backBufferLength: 0,
        liveSyncDurationCount: 3,
        liveMaxLatencyDurationCount: 8,
        maxBufferLength: 6,
        maxBufferSize: 8 * 1024 * 1024,
      });
      hlsRef.current = hls;

      hls.loadSource(streamUrl);
      hls.attachMedia(video);

      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        video.muted = isMuted;
        video
          .play()
          .then(() => {
            setIsPlaying(true);
            onPlaying?.();
          })
          .catch(() => {
            // Autoplay policy: try muted
            video.muted = true;
            video
              .play()
              .then(() => {
                setIsPlaying(true);
                onPlaying?.();
              })
              .catch(() => {});
          });
      });

      hls.on(Hls.Events.ERROR, (_event, data) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              hls.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              hls.recoverMediaError();
              break;
            default:
              setHasError(true);
              onError?.();
              hls.destroy();
              break;
          }
        }
      });
    } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
      // Safari / iOS HLS
      video.src = streamUrl;
      video.muted = isMuted;
      video
        .play()
        .then(() => {
          setIsPlaying(true);
          onPlaying?.();
        })
        .catch(() => {
          video.muted = true;
          video.play().catch(() => setHasError(true));
        });
    } else {
      setHasError(true);
    }

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
        hlsRef.current = null;
      }
    };
  }, [streamUrl]);

  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.muted = isMuted;
    }
  }, [isMuted]);

  return (
    <div className="relative w-full h-full overflow-hidden bg-black select-none">
      <video
        ref={videoRef}
        playsInline
        autoPlay
        muted={isMuted}
        poster={poster}
        className={`${className} transition-opacity duration-500 ${
          isPlaying ? "opacity-100" : "opacity-0"
        }`}
      />
      {(!isPlaying || hasError) && poster && (
        <img
          src={poster}
          alt="Live cam stream"
          className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-500 ${
            isPlaying ? "opacity-0 pointer-events-none" : "opacity-100"
          }`}
        />
      )}
    </div>
  );
}
