"use client";

import { useSearchParams } from "next/navigation";
import { useState, useEffect, Suspense } from "react";
import DuetViewer from "@/components/livecam/duet-viewer";
import Link from "next/link";

interface DuetSession {
  session_id: string;
  broadcaster1_id: number;
  broadcaster2_id: number;
  split_pct: number;
  status: string;
  broadcaster1: {
    id: number;
    username: string;
    profile_photo: string | null;
    viewer_count: number;
  };
  broadcaster2: {
    id: number;
    username: string;
    profile_photo: string | null;
    viewer_count: number;
  };
}

function DuetContent() {
  const searchParams = useSearchParams();
  const sessionId = searchParams.get("session");
  const [duetSession, setDuetSession] = useState<DuetSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!sessionId) {
      setLoading(false);
      return;
    }

    const loadSession = async () => {
      try {
        const res = await fetch(`/api/livecam/duet?session_id=${sessionId}`);
        const json = await res.json();
        if (json.error) {
          setError(json.error);
        } else {
          setDuetSession(json.data);
        }
      } catch {
        setError("Failed to load duet session");
      } finally {
        setLoading(false);
      }
    };

    loadSession();
  }, [sessionId]);

  if (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>
    );
  }

  if (!sessionId) {
    return (
      <div className="max-w-4xl mx-auto space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-white">Duet Dual-Cam</h1>
          <p className="text-text-muted mt-1">
            Watch two performers together in split-screen mode
          </p>
        </div>

        <div className="bg-surface rounded-xl border border-white/5 p-8 text-center space-y-4">
          <div className="w-20 h-20 mx-auto bg-surface-light rounded-full flex items-center justify-center">
            <svg className="w-10 h-10 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          </div>
          <h2 className="text-lg font-semibold text-white">No Active Duet Session</h2>
          <p className="text-text-muted text-sm max-w-md mx-auto">
            Duet sessions are started by broadcasters. Check LiveCam for active duet shows
            or wait for an invitation.
          </p>
          <Link
            href="/livecam"
            className="inline-block bg-gold hover:bg-gold-light text-black font-semibold px-6 py-3 rounded-lg transition-all"
          >
            Browse LiveCams
          </Link>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-4xl mx-auto space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-white">Duet Dual-Cam</h1>
          <p className="text-text-muted mt-1">Watch two performers together</p>
        </div>
        <div className="bg-surface rounded-xl border border-red-500/20 p-8 text-center space-y-4">
          <p className="text-red-400">{error}</p>
          <Link
            href="/livecam"
            className="inline-block bg-surface-light hover:bg-white/10 text-white font-semibold px-6 py-3 rounded-lg transition-all border border-white/10"
          >
            Back to LiveCam
          </Link>
        </div>
      </div>
    );
  }

  if (!duetSession) return null;

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <span className="bg-red-600 text-white text-xs font-bold px-2 py-0.5 rounded flex items-center gap-1">
              <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse" />
              LIVE DUET
            </span>
            {duetSession.broadcaster1.username} &amp; {duetSession.broadcaster2.username}
          </h1>
          <p className="text-text-muted mt-1 text-sm">
            Dual-cam split-screen show
          </p>
        </div>
        <Link
          href="/livecam"
          className="text-text-muted hover:text-white transition-colors text-sm"
        >
          Back to LiveCam
        </Link>
      </div>

      <DuetViewer
        duetSessionId={duetSession.session_id}
        broadcaster1={duetSession.broadcaster1}
        broadcaster2={duetSession.broadcaster2}
        splitPct={duetSession.split_pct}
      />
    </div>
  );
}

export default function DuetPage() {
  return (
    <Suspense
      fallback={
        <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>
      }
    >
      <DuetContent />
    </Suspense>
  );
}
