"use client";

import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState, useEffect, useRef, useCallback } from "react";

interface LiveSession {
  id: number;
  viewer_count: number;
  credits_earned: number;
  mode: string;
}

interface Viewer {
  user_id: number;
  username: string;
  mode: string;
}

export default function BroadcastPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const videoRef = useRef<HTMLVideoElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const debitRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const [broadcasting, setBroadcasting] = useState(false);
  const [liveSession, setLiveSession] = useState<LiveSession | null>(null);
  const [mode, setMode] = useState<"free" | "group" | "private">("free");
  const [viewers, setViewers] = useState<Viewer[]>([]);
  const [messages, setMessages] = useState<{ user: string; text: string }[]>([]);
  const [chatInput, setChatInput] = useState("");
  const [elapsed, setElapsed] = useState(0);
  const [creditsEarned, setCreditsEarned] = useState(0);
  const [cameraError, setCameraError] = useState("");

  // Auth guard
  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
    if (status === "authenticated") {
      const userType = (session?.user as Record<string, unknown>)?.userType;
      if (userType !== "escort") router.push("/dashboard");
    }
  }, [status, session, router]);

  // Initialize camera preview
  useEffect(() => {
    const initCamera = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { width: 1280, height: 720, facingMode: "user" },
          audio: true,
        });
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      } catch {
        setCameraError("Unable to access camera. Please allow camera permissions.");
      }
    };
    initCamera();

    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach((t) => t.stop());
      }
      if (timerRef.current) clearInterval(timerRef.current);
      if (debitRef.current) clearInterval(debitRef.current);
    };
  }, []);

  const startBroadcast = async () => {
    try {
      const res = await fetch("/api/livecam/start", { method: "POST" });
      const json = await res.json();
      if (!res.ok) {
        alert(json.error || "Failed to start broadcast");
        return;
      }
      setLiveSession(json.data);
      setBroadcasting(true);
      setElapsed(0);
      setCreditsEarned(0);

      // Start timer
      timerRef.current = setInterval(() => {
        setElapsed((prev) => prev + 1);
      }, 1000);

      // Start debit cycle (every 60 seconds)
      debitRef.current = setInterval(() => {
        debitAllPaidViewers(json.data.id);
      }, 60000);
    } catch {
      alert("Failed to start broadcast");
    }
  };

  const stopBroadcast = async () => {
    if (!liveSession) return;
    try {
      await fetch("/api/livecam/stop", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ session_id: liveSession.id }),
      });
    } catch {
      // Ignore errors on stop
    }
    setBroadcasting(false);
    setLiveSession(null);
    setViewers([]);
    if (timerRef.current) clearInterval(timerRef.current);
    if (debitRef.current) clearInterval(debitRef.current);
  };

  const debitAllPaidViewers = async (sessionId: number) => {
    for (const viewer of viewers) {
      if (viewer.mode !== "free") {
        try {
          const res = await fetch("/api/livecam/debit", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ session_id: sessionId, viewer_id: viewer.user_id }),
          });
          const json = await res.json();
          if (json.success) {
            setCreditsEarned((prev) => prev + 1);
          }
        } catch {
          // Continue with other viewers
        }
      }
    }
  };

  const kickViewer = useCallback(async (viewerUserId: number) => {
    if (!liveSession) return;
    try {
      await fetch("/api/livecam/kick", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ session_id: liveSession.id, viewer_user_id: viewerUserId }),
      });
      setViewers((prev) => prev.filter((v) => v.user_id !== viewerUserId));
    } catch {
      // Ignore
    }
  }, [liveSession]);

  const sendChat = () => {
    if (!chatInput.trim()) return;
    setMessages((prev) => [
      ...prev,
      { user: session?.user?.name || "You", text: chatInput.trim() },
    ]);
    setChatInput("");
  };

  const formatTime = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
  };

  const modeBadge = (m: string) => {
    const colors: Record<string, string> = {
      free: "bg-green-600",
      group: "bg-blue-600",
      private: "bg-purple-600",
    };
    return (
      <span className={`${colors[m] || "bg-gray-600"} text-white text-xs font-bold px-2 py-0.5 rounded uppercase`}>
        {m}
      </span>
    );
  };

  if (status === "loading") {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="w-8 h-8 border-2 border-gold border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-white">Broadcast Studio</h1>
        {broadcasting && (
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 bg-red-500 rounded-full animate-pulse" />
            <span className="text-red-400 font-semibold text-sm">LIVE</span>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Video + Controls */}
        <div className="lg:col-span-2 space-y-4">
          {/* Video */}
          <div className="relative bg-black rounded-xl overflow-hidden aspect-video">
            {cameraError ? (
              <div className="absolute inset-0 flex items-center justify-center text-red-400 text-sm p-4 text-center">
                {cameraError}
              </div>
            ) : (
              <video
                ref={videoRef}
                autoPlay
                muted
                playsInline
                className="w-full h-full object-cover"
              />
            )}
            {broadcasting && (
              <div className="absolute top-3 left-3 flex items-center gap-2">
                {modeBadge(mode)}
                <span className="bg-black/60 text-white text-xs font-mono px-2 py-0.5 rounded">
                  {formatTime(elapsed)}
                </span>
              </div>
            )}
          </div>

          {/* Controls */}
          <div className="flex flex-wrap gap-3">
            {!broadcasting ? (
              <button
                onClick={startBroadcast}
                disabled={!!cameraError}
                className="bg-gold hover:bg-gold-light text-black font-bold px-6 py-3 rounded-lg transition-all shadow-glow hover:shadow-lg disabled:opacity-50"
              >
                Start Broadcast
              </button>
            ) : (
              <button
                onClick={stopBroadcast}
                className="bg-red-600 hover:bg-red-700 text-white font-bold px-6 py-3 rounded-lg transition-all"
              >
                Stop Broadcast
              </button>
            )}

            {broadcasting && (
              <div className="flex gap-2">
                <button
                  onClick={() => setMode("free")}
                  className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
                    mode === "free"
                      ? "bg-green-600 text-white"
                      : "bg-surface-light text-text-muted hover:text-white"
                  }`}
                >
                  Free
                </button>
                <button
                  onClick={() => setMode("group")}
                  className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
                    mode === "group"
                      ? "bg-blue-600 text-white"
                      : "bg-surface-light text-text-muted hover:text-white"
                  }`}
                >
                  Group
                </button>
                <button
                  onClick={() => setMode("private")}
                  className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
                    mode === "private"
                      ? "bg-purple-600 text-white"
                      : "bg-surface-light text-text-muted hover:text-white"
                  }`}
                >
                  Private
                </button>
              </div>
            )}
          </div>

          {/* Stats */}
          {broadcasting && (
            <div className="grid grid-cols-3 gap-4">
              <div className="bg-surface rounded-lg border border-white/5 p-4 text-center">
                <p className="text-text-muted text-xs uppercase tracking-wider">Viewers</p>
                <p className="text-2xl font-bold text-white mt-1">{viewers.length}</p>
              </div>
              <div className="bg-surface rounded-lg border border-white/5 p-4 text-center">
                <p className="text-text-muted text-xs uppercase tracking-wider">Duration</p>
                <p className="text-2xl font-bold text-white mt-1 font-mono">{formatTime(elapsed)}</p>
              </div>
              <div className="bg-surface rounded-lg border border-white/5 p-4 text-center">
                <p className="text-text-muted text-xs uppercase tracking-wider">Earned</p>
                <p className="text-2xl font-bold text-gold mt-1">{creditsEarned}</p>
              </div>
            </div>
          )}
        </div>

        {/* Sidebar: Viewers + Chat */}
        <div className="space-y-4">
          {/* Viewers */}
          <div className="bg-surface rounded-xl border border-white/5 p-4">
            <h3 className="text-sm font-semibold text-white mb-3">
              Viewers ({viewers.length})
            </h3>
            {viewers.length === 0 ? (
              <p className="text-text-muted text-sm">No viewers yet</p>
            ) : (
              <div className="space-y-2 max-h-48 overflow-y-auto">
                {viewers.map((v) => (
                  <div
                    key={v.user_id}
                    className="flex items-center justify-between text-sm"
                  >
                    <div className="flex items-center gap-2">
                      <span className="text-white">{v.username}</span>
                      {modeBadge(v.mode)}
                    </div>
                    <button
                      onClick={() => kickViewer(v.user_id)}
                      className="text-red-400 hover:text-red-300 text-xs font-medium"
                    >
                      Kick
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Chat */}
          <div className="bg-surface rounded-xl border border-white/5 p-4 flex flex-col h-80">
            <h3 className="text-sm font-semibold text-white mb-3">Chat</h3>
            <div className="flex-1 overflow-y-auto space-y-2 mb-3">
              {messages.length === 0 ? (
                <p className="text-text-muted text-sm">No messages yet</p>
              ) : (
                messages.map((m, i) => (
                  <div key={i} className="text-sm">
                    <span className="text-gold font-medium">{m.user}: </span>
                    <span className="text-white">{m.text}</span>
                  </div>
                ))
              )}
            </div>
            <div className="flex gap-2">
              <input
                type="text"
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && sendChat()}
                placeholder="Type a message..."
                className="flex-1 bg-surface-light border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-text-muted focus:outline-none focus:ring-1 focus:ring-gold/50"
              />
              <button
                onClick={sendChat}
                className="bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2 rounded-lg text-sm transition-all"
              >
                Send
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
