"use client";

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

export default function HostStreamPage() {
  const { streamId } = useParams<{ streamId: string }>();
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isLive, setIsLive] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [streamInfo, setStreamInfo] = useState<{ sdp_url?: string; name?: string } | null>(null);
  const pcRef = useRef<RTCPeerConnection | null>(null);

  useEffect(() => {
    fetch(`/api/streams/${streamId}`)
      .then((r) => r.json())
      .then((data) => setStreamInfo(data))
      .catch(() => setError("Failed to load stream info."));
  }, [streamId]);

  const startStream = useCallback(async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: 1920, height: 1080 },
        audio: true,
      });
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }

      // Start the stream via API
      await fetch(`/api/streams/${streamId}/start`, { method: "POST" });

      // Set up WebRTC peer connection
      const pc = new RTCPeerConnection({
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
      });
      pcRef.current = pc;

      stream.getTracks().forEach((track) => pc.addTrack(track, stream));

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

      // Send offer to Wowza SDP URL
      if (streamInfo?.sdp_url) {
        const res = await fetch(streamInfo.sdp_url, {
          method: "POST",
          headers: { "Content-Type": "application/sdp" },
          body: offer.sdp,
        });
        const answerSdp = await res.text();
        await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
      }

      setIsLive(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to start stream.");
    }
  }, [streamId, streamInfo]);

  async function stopStream() {
    try {
      if (pcRef.current) {
        pcRef.current.close();
        pcRef.current = null;
      }
      if (videoRef.current?.srcObject) {
        (videoRef.current.srcObject as MediaStream).getTracks().forEach((t) => t.stop());
        videoRef.current.srcObject = null;
      }
      await fetch(`/api/streams/${streamId}/stop`, { method: "POST" });
      setIsLive(false);
    } catch {
      setError("Failed to stop 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">Host Stream</h1>
          <p className="text-text-muted text-sm">{streamInfo?.name || streamId}</p>
        </div>
        {isLive && (
          <span className="bg-red-600 text-white text-sm px-3 py-1 rounded-full font-semibold animate-pulse">
            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 mb-4">
        <video
          ref={videoRef}
          autoPlay
          muted
          playsInline
          className="w-full aspect-video bg-black"
        />
      </div>

      <div className="flex gap-3">
        {!isLive ? (
          <button
            onClick={startStream}
            className="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors"
          >
            Go Live
          </button>
        ) : (
          <button
            onClick={stopStream}
            className="bg-surface-light hover:bg-red-600 text-text hover:text-white px-6 py-3 rounded-lg font-semibold transition-colors"
          >
            End Stream
          </button>
        )}
      </div>
    </div>
  );
}
