"use client";

import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";

export default function PlayStreamPage() {
  const { streamId } = useParams<{ streamId: string }>();
  const videoRef = useRef<HTMLVideoElement>(null);
  const pcRef = useRef<RTCPeerConnection | null>(null);
  const [streamInfo, setStreamInfo] = useState<{ name?: string; sdp_url?: string; state?: string } | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [connected, setConnected] = useState(false);
  const [muted, setMuted] = useState(true);

  useEffect(() => {
    let cancelled = false;
    fetch(`/api/streams/${streamId}`)
      .then((r) => r.json())
      .then((data) => {
        if (cancelled) return;
        setStreamInfo(data);
        if (data.sdp_url) connectToStream(data.sdp_url);
      })
      .catch(() => {
        if (!cancelled) setError("Failed to load stream info.");
      });
    return () => {
      cancelled = true;
      // Tear down the WebRTC connection on unmount or streamId change.
      // Without this the pc stayed open, MediaStream tracks lingered, and
      // the video element kept its srcObject — both leaks.
      if (pcRef.current) {
        try { pcRef.current.close(); } catch { /* noop */ }
        pcRef.current = null;
      }
      const vid = videoRef.current;
      if (vid?.srcObject) {
        const stream = vid.srcObject as MediaStream;
        stream.getTracks().forEach((t) => t.stop());
        vid.srcObject = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [streamId]);

  async function connectToStream(sdpUrl: string) {
    try {
      const pc = new RTCPeerConnection({
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
      });
      pcRef.current = pc;

      pc.ontrack = (event) => {
        if (videoRef.current && event.streams[0]) {
          videoRef.current.srcObject = event.streams[0];
          setConnected(true);
        }
      };

      // Add transceiver for receiving
      pc.addTransceiver("video", { direction: "recvonly" });
      pc.addTransceiver("audio", { direction: "recvonly" });

      const offer = await pc.createOffer();
      await pc.setLocalDescription(offer);

      const res = await fetch(sdpUrl, {
        method: "POST",
        headers: { "Content-Type": "application/sdp" },
        body: offer.sdp,
      });
      const answerSdp = await res.text();
      await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to connect to stream.");
    }
  }

  return (
    <div className="max-w-4xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-text">{streamInfo?.name || "Live Stream"}</h1>
          <p className="text-text-muted text-sm">
            {connected ? "Connected" : streamInfo?.state === "started" ? "Connecting..." : "Stream offline"}
          </p>
        </div>
        {connected && (
          <span className="bg-red-600 text-white text-sm px-3 py-1 rounded-full font-semibold">
            LIVE
          </span>
        )}
      </div>

      {error && (
        <div className="bg-red-900/20 border border-red-800 rounded-lg p-4 mb-4 text-red-400">
          {error}
        </div>
      )}

      <div className="bg-surface rounded-lg overflow-hidden relative">
        <video
          ref={videoRef}
          autoPlay
          playsInline
          muted={muted}
          className="w-full aspect-video bg-black"
        />
        {connected && muted && (
          // Browsers block unmuted autoplay, so we start muted and offer a
          // one-click unmute affordance after the stream is playing.
          <button
            onClick={() => {
              setMuted(false);
              if (videoRef.current) videoRef.current.muted = false;
            }}
            className="absolute bottom-3 right-3 bg-black/70 hover:bg-black/90 text-white text-sm px-3 py-1.5 rounded-lg backdrop-blur-sm"
          >
            🔇 Click to unmute
          </button>
        )}
      </div>

      {!connected && !error && (
        <div className="mt-4 text-center">
          <p className="text-text-muted">Waiting for stream to start...</p>
        </div>
      )}
    </div>
  );
}
