"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useConfirm } from "@/components/shared/use-confirm";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";

interface StreamInfo {
  id: string;
  name: string;
  state: string;
}

export default function ManageWebcamPage() {
  const [streams, setStreams] = useState<StreamInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [streamName, setStreamName] = useState("");
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  useEffect(() => {
    // Earlier this called /api/manage/webcam which never existed — every
    // GET/POST/DELETE silently 404'd. /api/streams is the real broadcaster
    // endpoint and already enforces session-scoped access.
    fetch("/api/streams")
      .then((r) => r.json())
      .then((data) => setStreams(data.data || []))
      .finally(() => setLoading(false));
  }, []);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!streamName.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/api/streams", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: streamName }),
      });
      if (!res.ok) throw new Error("Failed");
      const data = await res.json();
      setStreams((prev) => [data.data ?? data.stream, ...prev]);
      setStreamName("");
    } catch {
      alert("Failed to create stream.");
    } finally {
      setCreating(false);
    }
  }

  async function handleDelete(id: string) {
    if (!(await askConfirm({ title: "Delete stream", message: "Delete this stream?" }))) return;
    try {
      await fetch(`/api/streams/${id}`, { method: "DELETE" });
      setStreams((prev) => prev.filter((s) => s.id !== id));
    } catch {
      alert("Failed to delete stream.");
    }
  }

  if (loading) return <ManagePageSkeleton />;

  return (
    <div className="max-w-2xl mx-auto">
      {confirmDialog}
      <h1 className="text-3xl font-bold text-text mb-6">Webcam / Streaming</h1>

      <form onSubmit={handleCreate} className="bg-surface rounded-lg p-6 mb-6">
        <h2 className="text-lg font-semibold text-text mb-3">Create New Stream</h2>
        <div className="flex gap-3">
          <input
            type="text"
            value={streamName}
            onChange={(e) => setStreamName(e.target.value)}
            placeholder="Stream name"
            className="flex-1 bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <button
            type="submit"
            disabled={creating}
            className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {creating ? "Creating..." : "Create"}
          </button>
        </div>
      </form>

      <div className="space-y-3">
        {streams.length === 0 ? (
          <div className="bg-surface rounded-lg p-8 text-center text-text-muted">
            No streams created yet.
          </div>
        ) : (
          streams.map((stream) => (
            <div key={stream.id} className="bg-surface rounded-lg p-4 flex items-center justify-between">
              <div>
                <h3 className="font-semibold text-text">{stream.name}</h3>
                <span className={`text-xs ${stream.state === "started" ? "text-green-400" : "text-text-muted"}`}>
                  {stream.state}
                </span>
              </div>
              <div className="flex gap-2">
                <Link
                  href={`/streams/host/${stream.id}`}
                  className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
                >
                  Go Live
                </Link>
                <button
                  onClick={() => handleDelete(stream.id)}
                  className="text-red-400 hover:text-red-300 text-sm px-3 py-2"
                >
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
