"use client";

import { useState } from "react";
import Image from "next/image";

interface Broadcaster {
  id: number;
  username: string;
  profile_photo: string | null;
  viewer_count: number;
}

interface DuetViewerProps {
  duetSessionId: string;
  broadcaster1: Broadcaster;
  broadcaster2: Broadcaster;
  splitPct?: number;
}

export default function DuetViewer({
  duetSessionId,
  broadcaster1,
  broadcaster2,
  splitPct = 50,
}: DuetViewerProps) {
  const [chatMessages, setChatMessages] = useState<
    { user: string; text: string; time: string }[]
  >([]);
  const [chatInput, setChatInput] = useState("");
  const [tipping, setTipping] = useState<string | null>(null);
  const [tipAmount, setTipAmount] = useState(10);

  const handleSendChat = (e: React.FormEvent) => {
    e.preventDefault();
    const text = chatInput.trim();
    if (!text) return;
    setChatMessages((prev) => [
      ...prev,
      {
        user: "You",
        text,
        time: new Date().toLocaleTimeString([], {
          hour: "2-digit",
          minute: "2-digit",
        }),
      },
    ]);
    setChatInput("");
  };

  const handleTip = async (target: "left" | "right" | "both") => {
    setTipping(target);
    try {
      await fetch("/api/livecam/duet", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "tip",
          session_id: duetSessionId,
          target,
          amount: tipAmount,
        }),
      });
    } catch {
      // Tip failed silently
    } finally {
      setTipping(null);
    }
  };

  const splitLeft = splitPct;
  const splitRight = 100 - splitPct;

  return (
    <div className="space-y-4">
      {/* Split-Screen Streams */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
        {/* Broadcaster 1 (Left) */}
        <div className="relative aspect-video bg-black rounded-lg overflow-hidden group">
          <div className="absolute inset-0 flex items-center justify-center">
            {broadcaster1.profile_photo ? (
              <Image
                src={broadcaster1.profile_photo}
                alt={broadcaster1.username}
                fill
                sizes="(max-width:1024px) 100vw, 50vw"
                className="object-cover opacity-30"
              />
            ) : null}
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="text-center">
                <div className="w-12 h-12 border-2 border-gold border-t-transparent rounded-full animate-spin mx-auto mb-3" />
                <p className="text-white/70 text-sm">Connecting to stream...</p>
              </div>
            </div>
          </div>

          {/* Overlay Info */}
          <div className="absolute top-3 left-3 flex items-center gap-2">
            <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
            </span>
            <span className="bg-black/60 text-white text-sm font-medium px-2 py-0.5 rounded">
              {broadcaster1.username}
            </span>
          </div>
          <div className="absolute bottom-3 right-3 bg-black/60 text-white text-xs px-2 py-0.5 rounded flex items-center gap-1">
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
              <path
                fillRule="evenodd"
                d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
                clipRule="evenodd"
              />
            </svg>
            {broadcaster1.viewer_count}
          </div>
        </div>

        {/* Broadcaster 2 (Right) */}
        <div className="relative aspect-video bg-black rounded-lg overflow-hidden group">
          <div className="absolute inset-0 flex items-center justify-center">
            {broadcaster2.profile_photo ? (
              <Image
                src={broadcaster2.profile_photo}
                alt={broadcaster2.username}
                fill
                sizes="(max-width:1024px) 100vw, 50vw"
                className="object-cover opacity-30"
              />
            ) : null}
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="text-center">
                <div className="w-12 h-12 border-2 border-gold border-t-transparent rounded-full animate-spin mx-auto mb-3" />
                <p className="text-white/70 text-sm">Connecting to stream...</p>
              </div>
            </div>
          </div>

          {/* Overlay Info */}
          <div className="absolute top-3 left-3 flex items-center gap-2">
            <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
            </span>
            <span className="bg-black/60 text-white text-sm font-medium px-2 py-0.5 rounded">
              {broadcaster2.username}
            </span>
          </div>
          <div className="absolute bottom-3 right-3 bg-black/60 text-white text-xs px-2 py-0.5 rounded flex items-center gap-1">
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
              <path
                fillRule="evenodd"
                d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
                clipRule="evenodd"
              />
            </svg>
            {broadcaster2.viewer_count}
          </div>
        </div>
      </div>

      {/* Revenue Split Indicator */}
      <div className="bg-surface rounded-lg border border-white/5 p-3">
        <div className="flex items-center justify-between text-xs text-text-muted mb-2">
          <span>{broadcaster1.username} ({splitLeft}%)</span>
          <span className="text-gold font-medium">
            {splitLeft === 50 ? "Tips split 50/50" : `Custom split ${splitLeft}/${splitRight}`}
          </span>
          <span>{broadcaster2.username} ({splitRight}%)</span>
        </div>
        <div className="w-full h-2 bg-surface-light rounded-full overflow-hidden flex">
          <div
            className="h-full bg-gold rounded-l-full transition-all"
            style={{ width: `${splitLeft}%` }}
          />
          <div
            className="h-full bg-purple-500 rounded-r-full transition-all"
            style={{ width: `${splitRight}%` }}
          />
        </div>
      </div>

      {/* Tip Buttons */}
      <div className="flex flex-col sm:flex-row gap-2">
        <div className="flex-1 flex items-center gap-2">
          <label className="text-sm text-text-muted whitespace-nowrap">Amount:</label>
          <input
            type="number"
            min={1}
            value={tipAmount}
            onChange={(e) => setTipAmount(Math.max(1, Number(e.target.value)))}
            className="w-20 bg-surface-light border border-white/10 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-gold/50"
          />
          <span className="text-xs text-text-muted">credits</span>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => handleTip("left")}
            disabled={tipping === "left"}
            className="flex-1 sm:flex-none bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2 rounded-lg transition-all text-sm disabled:opacity-50"
          >
            {tipping === "left" ? "..." : `Tip ${broadcaster1.username}`}
          </button>
          <button
            onClick={() => handleTip("right")}
            disabled={tipping === "right"}
            className="flex-1 sm:flex-none bg-purple-600 hover:bg-purple-500 text-white font-semibold px-4 py-2 rounded-lg transition-all text-sm disabled:opacity-50"
          >
            {tipping === "right" ? "..." : `Tip ${broadcaster2.username}`}
          </button>
          <button
            onClick={() => handleTip("both")}
            disabled={tipping === "both"}
            className="flex-1 sm:flex-none bg-gradient-to-r from-gold to-purple-600 hover:from-gold-light hover:to-purple-500 text-white font-semibold px-4 py-2 rounded-lg transition-all text-sm disabled:opacity-50"
          >
            {tipping === "both" ? "..." : "Tip Both"}
          </button>
        </div>
      </div>

      {/* Unified Chat */}
      <div className="bg-surface rounded-lg border border-white/5 overflow-hidden">
        <div className="p-3 border-b border-white/5">
          <h3 className="text-sm font-semibold text-white">Duet Chat</h3>
        </div>
        <div className="h-48 overflow-y-auto p-3 space-y-2 scrollbar-thin scrollbar-thumb-surface-light">
          {chatMessages.length === 0 ? (
            <p className="text-text-muted text-sm text-center py-8">
              No messages yet. Say hi to both performers!
            </p>
          ) : (
            chatMessages.map((msg, i) => (
              <div key={i} className="flex gap-2 text-sm">
                <span className="text-gold font-medium shrink-0">{msg.user}</span>
                <span className="text-white">{msg.text}</span>
                <span className="text-text-muted text-xs ml-auto shrink-0">{msg.time}</span>
              </div>
            ))
          )}
        </div>
        <form onSubmit={handleSendChat} className="p-3 border-t border-white/5 flex gap-2">
          <input
            type="text"
            value={chatInput}
            onChange={(e) => setChatInput(e.target.value)}
            placeholder="Type a message..."
            className="flex-1 bg-surface-light border border-white/10 rounded-lg px-3 py-2 text-white text-sm placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50"
          />
          <button
            type="submit"
            className="bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2 rounded-lg transition-all text-sm"
          >
            Send
          </button>
        </form>
      </div>
    </div>
  );
}
