"use client";

import { useState, useEffect, useCallback, useRef } from "react";

interface TipGoalConfig {
  goal: number;
  current: number;
  label?: string;
}

interface PollOption {
  text: string;
  votes: number;
}

interface PollConfig {
  question: string;
  options: PollOption[];
  voted_users: number[];
}

interface TimerConfig {
  label: string;
  ends_at: string; // ISO timestamp
}

interface Overlay {
  id: number;
  session_id: number;
  broadcaster_id: number;
  type: "tip_goal" | "poll" | "timer";
  config: TipGoalConfig | PollConfig | TimerConfig;
  active: boolean;
  created_at: string;
}

interface StreamOverlaysProps {
  broadcasterId: number;
  isHost: boolean;
  sessionId?: number;
}

// ─── Tip Goal Bar ────────────────────────────────────────────────────────────

function TipGoalOverlay({ config }: { config: TipGoalConfig }) {
  const pct = Math.min(100, Math.round((config.current / config.goal) * 100));
  const remaining = Math.max(0, config.goal - config.current);

  return (
    <div className="absolute bottom-3 left-3 right-3 pointer-events-none">
      <div className="bg-black/60 backdrop-blur-sm rounded-lg px-4 py-3 border border-gold/30">
        <div className="flex items-center justify-between text-xs text-white/80 mb-1.5">
          <span className="font-semibold text-gold">
            {config.label || "Tip Goal"}
          </span>
          <span>
            {config.current} / {config.goal} credits
            <span className="text-white/50 ml-2">({remaining} to go)</span>
          </span>
        </div>
        <div className="w-full h-3 bg-white/10 rounded-full overflow-hidden">
          <div
            className="h-full rounded-full transition-all duration-700 ease-out"
            style={{
              width: `${pct}%`,
              background: "linear-gradient(90deg, #b8860b, #ffd700, #ffe066)",
            }}
          />
        </div>
        <div className="text-center text-[10px] text-white/60 mt-1">
          {pct}% complete
        </div>
      </div>
    </div>
  );
}

// ─── Poll ────────────────────────────────────────────────────────────────────

function PollOverlay({
  overlay,
  isHost,
  userId,
  onVote,
}: {
  overlay: Overlay;
  isHost: boolean;
  userId: number | null;
  onVote: (overlayId: number, optionIndex: number) => void;
}) {
  const config = overlay.config as PollConfig;
  const totalVotes = config.options.reduce((sum, o) => sum + o.votes, 0);
  const hasVoted =
    userId !== null && config.voted_users?.includes(userId);

  return (
    <div className="absolute top-14 right-3 w-64 pointer-events-auto">
      <div className="bg-black/70 backdrop-blur-sm rounded-xl border border-white/10 p-4 shadow-lg">
        <p className="text-sm font-semibold text-white mb-3">
          {config.question}
        </p>
        <div className="space-y-2">
          {config.options.map((opt, i) => {
            const pct = totalVotes > 0 ? Math.round((opt.votes / totalVotes) * 100) : 0;
            const canVote = !isHost && !hasVoted && userId !== null;

            return (
              <button
                key={i}
                disabled={!canVote}
                onClick={() => canVote && onVote(overlay.id, i)}
                className={`relative w-full text-left rounded-lg overflow-hidden transition-all ${
                  canVote
                    ? "hover:ring-1 hover:ring-gold/50 cursor-pointer"
                    : "cursor-default"
                }`}
              >
                <div className="relative z-10 flex items-center justify-between px-3 py-2 text-xs text-white">
                  <span>{opt.text}</span>
                  <span className="text-white/60 font-mono">{opt.votes}</span>
                </div>
                <div
                  className="absolute inset-0 bg-gold/20 transition-all duration-500"
                  style={{ width: `${pct}%` }}
                />
                <div className="absolute inset-0 bg-white/5" />
              </button>
            );
          })}
        </div>
        <p className="text-[10px] text-white/40 mt-2 text-center">
          {totalVotes} vote{totalVotes !== 1 ? "s" : ""}
          {hasVoted && " — you voted"}
        </p>
      </div>
    </div>
  );
}

// ─── Countdown Timer ─────────────────────────────────────────────────────────

function TimerOverlay({ config }: { config: TimerConfig }) {
  const [remaining, setRemaining] = useState(0);

  useEffect(() => {
    const calc = () => {
      const diff = Math.max(
        0,
        Math.floor((new Date(config.ends_at).getTime() - Date.now()) / 1000)
      );
      setRemaining(diff);
    };
    calc();
    const interval = setInterval(calc, 1000);
    return () => clearInterval(interval);
  }, [config.ends_at]);

  if (remaining <= 0) return null;

  const mins = Math.floor(remaining / 60);
  const secs = remaining % 60;
  const isUrgent = remaining < 30;

  return (
    <div className="absolute top-3 left-1/2 -translate-x-1/2 pointer-events-none">
      <div
        className={`bg-black/70 backdrop-blur-sm rounded-xl border px-5 py-2.5 shadow-lg transition-all ${
          isUrgent
            ? "border-red-500/60 animate-pulse"
            : "border-white/10"
        }`}
      >
        <p className="text-[10px] text-white/60 text-center mb-0.5">
          {config.label || "Countdown"}
        </p>
        <p
          className={`text-2xl font-mono font-bold text-center ${
            isUrgent ? "text-red-400" : "text-white"
          }`}
        >
          {String(mins).padStart(2, "0")}:{String(secs).padStart(2, "0")}
        </p>
      </div>
    </div>
  );
}

// ─── Host Controls ───────────────────────────────────────────────────────────

function HostControls({
  overlays,
  sessionId,
  onRefresh,
}: {
  overlays: Overlay[];
  sessionId: number;
  onRefresh: () => void;
}) {
  const [creating, setCreating] = useState<"tip_goal" | "poll" | "timer" | null>(null);

  // Tip goal form
  const [goalAmount, setGoalAmount] = useState("500");
  const [goalLabel, setGoalLabel] = useState("");

  // Poll form
  const [pollQuestion, setPollQuestion] = useState("");
  const [pollOptions, setPollOptions] = useState(["", ""]);

  // Timer form
  const [timerMinutes, setTimerMinutes] = useState("5");
  const [timerLabel, setTimerLabel] = useState("");

  const [submitting, setSubmitting] = useState(false);

  const resetForms = () => {
    setCreating(null);
    setGoalAmount("500");
    setGoalLabel("");
    setPollQuestion("");
    setPollOptions(["", ""]);
    setTimerMinutes("5");
    setTimerLabel("");
  };

  const createOverlay = async (type: string, config: Record<string, unknown>) => {
    setSubmitting(true);
    try {
      const res = await fetch("/api/livecam/overlays", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ session_id: sessionId, type, config }),
      });
      if (res.ok) {
        resetForms();
        onRefresh();
      }
    } finally {
      setSubmitting(false);
    }
  };

  const removeOverlay = async (id: number) => {
    await fetch(`/api/livecam/overlays?id=${id}`, { method: "DELETE" });
    onRefresh();
  };

  const handleCreateTipGoal = () => {
    const goal = Math.max(1, Number(goalAmount) || 500);
    createOverlay("tip_goal", { goal, current: 0, label: goalLabel || "Tip Goal" });
  };

  const handleCreatePoll = () => {
    const validOptions = pollOptions.filter((o) => o.trim());
    if (!pollQuestion.trim() || validOptions.length < 2) return;
    createOverlay("poll", {
      question: pollQuestion.trim(),
      options: validOptions.map((text) => ({ text: text.trim(), votes: 0 })),
      voted_users: [],
    });
  };

  const handleCreateTimer = () => {
    const mins = Math.max(1, Math.min(120, Number(timerMinutes) || 5));
    const endsAt = new Date(Date.now() + mins * 60 * 1000).toISOString();
    createOverlay("timer", { label: timerLabel || "Countdown", ends_at: endsAt });
  };

  return (
    <div className="mt-3 space-y-3">
      <div className="flex items-center justify-between">
        <h4 className="text-xs font-semibold text-white/70 uppercase tracking-wide">
          Stream Overlays
        </h4>
      </div>

      {/* Active overlays list */}
      {overlays.length > 0 && (
        <div className="space-y-1.5">
          {overlays.map((o) => (
            <div
              key={o.id}
              className="flex items-center justify-between bg-white/5 rounded-lg px-3 py-2 text-xs"
            >
              <span className="text-white">
                {o.type === "tip_goal" && `Goal: ${(o.config as TipGoalConfig).goal} credits`}
                {o.type === "poll" && `Poll: ${(o.config as PollConfig).question}`}
                {o.type === "timer" && `Timer: ${(o.config as TimerConfig).label}`}
              </span>
              <button
                onClick={() => removeOverlay(o.id)}
                className="text-red-400 hover:text-red-300 font-medium ml-2"
              >
                Remove
              </button>
            </div>
          ))}
        </div>
      )}

      {/* Add buttons */}
      {!creating && (
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => setCreating("tip_goal")}
            className="bg-gold/20 hover:bg-gold/30 border border-gold/30 text-gold text-xs font-semibold px-3 py-1.5 rounded-lg transition-all"
          >
            + Tip Goal
          </button>
          <button
            onClick={() => setCreating("poll")}
            className="bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/30 text-blue-400 text-xs font-semibold px-3 py-1.5 rounded-lg transition-all"
          >
            + Poll
          </button>
          <button
            onClick={() => setCreating("timer")}
            className="bg-purple-500/20 hover:bg-purple-500/30 border border-purple-500/30 text-purple-400 text-xs font-semibold px-3 py-1.5 rounded-lg transition-all"
          >
            + Timer
          </button>
        </div>
      )}

      {/* Tip Goal Form */}
      {creating === "tip_goal" && (
        <div className="bg-white/5 rounded-lg p-3 space-y-2">
          <p className="text-xs font-semibold text-gold">New Tip Goal</p>
          <input
            type="text"
            placeholder="Label (optional)"
            value={goalLabel}
            onChange={(e) => setGoalLabel(e.target.value)}
            className="w-full bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-gold/50"
          />
          <input
            type="number"
            placeholder="Goal amount (credits)"
            value={goalAmount}
            onChange={(e) => setGoalAmount(e.target.value)}
            className="w-full bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-gold/50"
          />
          <div className="flex gap-2">
            <button
              onClick={handleCreateTipGoal}
              disabled={submitting}
              className="bg-gold hover:bg-gold-light text-black text-xs font-bold px-4 py-1.5 rounded-lg transition-all disabled:opacity-50"
            >
              Create
            </button>
            <button
              onClick={resetForms}
              className="text-white/50 hover:text-white text-xs px-3 py-1.5"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Poll Form */}
      {creating === "poll" && (
        <div className="bg-white/5 rounded-lg p-3 space-y-2">
          <p className="text-xs font-semibold text-blue-400">New Poll</p>
          <input
            type="text"
            placeholder="Question"
            value={pollQuestion}
            onChange={(e) => setPollQuestion(e.target.value)}
            className="w-full bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-blue-500/50"
          />
          {pollOptions.map((opt, i) => (
            <div key={i} className="flex gap-2">
              <input
                type="text"
                placeholder={`Option ${i + 1}`}
                value={opt}
                onChange={(e) => {
                  const next = [...pollOptions];
                  next[i] = e.target.value;
                  setPollOptions(next);
                }}
                className="flex-1 bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-blue-500/50"
              />
              {i >= 2 && (
                <button
                  onClick={() => setPollOptions(pollOptions.filter((_, j) => j !== i))}
                  className="text-red-400 hover:text-red-300 text-xs px-2"
                >
                  X
                </button>
              )}
            </div>
          ))}
          {pollOptions.length < 4 && (
            <button
              onClick={() => setPollOptions([...pollOptions, ""])}
              className="text-blue-400 hover:text-blue-300 text-xs"
            >
              + Add option
            </button>
          )}
          <div className="flex gap-2">
            <button
              onClick={handleCreatePoll}
              disabled={submitting || !pollQuestion.trim() || pollOptions.filter((o) => o.trim()).length < 2}
              className="bg-blue-500 hover:bg-blue-400 text-white text-xs font-bold px-4 py-1.5 rounded-lg transition-all disabled:opacity-50"
            >
              Create
            </button>
            <button
              onClick={resetForms}
              className="text-white/50 hover:text-white text-xs px-3 py-1.5"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Timer Form */}
      {creating === "timer" && (
        <div className="bg-white/5 rounded-lg p-3 space-y-2">
          <p className="text-xs font-semibold text-purple-400">New Timer</p>
          <input
            type="text"
            placeholder="Label (optional)"
            value={timerLabel}
            onChange={(e) => setTimerLabel(e.target.value)}
            className="w-full bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-purple-500/50"
          />
          <input
            type="number"
            placeholder="Minutes"
            value={timerMinutes}
            onChange={(e) => setTimerMinutes(e.target.value)}
            min={1}
            max={120}
            className="w-full bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-white/30 focus:outline-none focus:ring-1 focus:ring-purple-500/50"
          />
          <div className="flex gap-2">
            <button
              onClick={handleCreateTimer}
              disabled={submitting}
              className="bg-purple-500 hover:bg-purple-400 text-white text-xs font-bold px-4 py-1.5 rounded-lg transition-all disabled:opacity-50"
            >
              Create
            </button>
            <button
              onClick={resetForms}
              className="text-white/50 hover:text-white text-xs px-3 py-1.5"
            >
              Cancel
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Custom Hook for shared overlay state ────────────────────────────────────

export function useStreamOverlays(sessionId: number | undefined) {
  const [overlays, setOverlays] = useState<Overlay[]>([]);
  const [userId, setUserId] = useState<number | null>(null);
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fetchOverlays = useCallback(async () => {
    if (!sessionId) return;
    try {
      const res = await fetch(`/api/livecam/overlays?session_id=${sessionId}`);
      if (res.ok) {
        const json = await res.json();
        setOverlays(json.data || []);
        if (json.user_id) setUserId(json.user_id);
      }
    } catch {
      // Silently fail — overlays are non-critical
    }
  }, [sessionId]);

  // Poll for updates every 5 seconds
  useEffect(() => {
    fetchOverlays();
    pollRef.current = setInterval(fetchOverlays, 5000);
    return () => {
      if (pollRef.current) clearInterval(pollRef.current);
    };
  }, [fetchOverlays]);

  const handleVote = async (overlayId: number, optionIndex: number) => {
    try {
      const res = await fetch("/api/livecam/overlays/vote", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ overlay_id: overlayId, option_index: optionIndex }),
      });
      if (res.ok) {
        fetchOverlays();
      }
    } catch {
      // Ignore
    }
  };

  const activeOverlays = overlays.filter((o) => o.active);

  return { activeOverlays, userId, handleVote, fetchOverlays };
}

// ─── Overlay Layer (renders inside video container) ──────────────────────────

export function StreamOverlayLayer({
  overlays,
  isHost,
  userId,
  onVote,
}: {
  overlays: Overlay[];
  isHost: boolean;
  userId: number | null;
  onVote: (overlayId: number, optionIndex: number) => void;
}) {
  if (overlays.length === 0) return null;

  return (
    <div className="absolute inset-0 z-10 pointer-events-none rounded-xl">
      {overlays.map((overlay) => {
        switch (overlay.type) {
          case "tip_goal":
            return (
              <TipGoalOverlay
                key={overlay.id}
                config={overlay.config as TipGoalConfig}
              />
            );
          case "poll":
            return (
              <PollOverlay
                key={overlay.id}
                overlay={overlay}
                isHost={isHost}
                userId={userId}
                onVote={onVote}
              />
            );
          case "timer":
            return (
              <TimerOverlay
                key={overlay.id}
                config={overlay.config as TimerConfig}
              />
            );
          default:
            return null;
        }
      })}
    </div>
  );
}

// ─── Host Controls Panel (renders outside video container) ───────────────────

export function StreamOverlayControls({
  overlays,
  sessionId,
  onRefresh,
}: {
  overlays: Overlay[];
  sessionId: number;
  onRefresh: () => void;
}) {
  return (
    <HostControls overlays={overlays} sessionId={sessionId} onRefresh={onRefresh} />
  );
}

// ─── Default Export (convenience wrapper) ────────────────────────────────────

export default function StreamOverlays({
  broadcasterId,
  isHost,
  sessionId,
}: StreamOverlaysProps) {
  const { activeOverlays, userId, handleVote, fetchOverlays } = useStreamOverlays(sessionId);

  return (
    <>
      <StreamOverlayLayer
        overlays={activeOverlays}
        isHost={isHost}
        userId={userId}
        onVote={handleVote}
      />
      {isHost && sessionId && (
        <StreamOverlayControls
          overlays={activeOverlays}
          sessionId={sessionId}
          onRefresh={fetchOverlays}
        />
      )}
    </>
  );
}
