"use client";

import { useEffect, useState } from "react";

interface Server {
  id: string;
  url: string;
  label?: string;
  active: boolean;
  order: number;
}

const KEY_STORE = "arvio.admin.key";

export default function AdminPage() {
  const [key, setKey] = useState("");
  const [authed, setAuthed] = useState(false);
  const [servers, setServers] = useState<Server[]>([]);
  const [url, setUrl] = useState("");
  const [label, setLabel] = useState("");
  const [err, setErr] = useState("");

  useEffect(() => {
    const k = localStorage.getItem(KEY_STORE);
    if (k) { setKey(k); void load(k); }
  }, []);

  async function load(k: string) {
    setErr("");
    const res = await fetch("/api/panel/servers", { headers: { "x-admin-key": k } });
    if (res.ok) {
      const j = await res.json();
      setServers(j.servers ?? []);
      setAuthed(true);
      localStorage.setItem(KEY_STORE, k);
    } else {
      setAuthed(false);
      setErr("Clave incorrecta.");
    }
  }

  async function add() {
    setErr("");
    const res = await fetch("/api/panel/servers", {
      method: "POST",
      headers: { "x-admin-key": key, "Content-Type": "application/json" },
      body: JSON.stringify({ url, label })
    });
    if (res.ok) { setUrl(""); setLabel(""); void load(key); }
    else setErr((await res.json()).error ?? "Error");
  }

  async function patch(id: string, body: Record<string, unknown>) {
    await fetch(`/api/panel/servers/${id}`, {
      method: "PATCH",
      headers: { "x-admin-key": key, "Content-Type": "application/json" },
      body: JSON.stringify(body)
    });
    void load(key);
  }

  async function del(id: string) {
    if (!confirm("¿Eliminar este servidor?")) return;
    await fetch(`/api/panel/servers/${id}`, { method: "DELETE", headers: { "x-admin-key": key } });
    void load(key);
  }

  const box: React.CSSProperties = { maxWidth: 820, margin: "40px auto", padding: 24, fontFamily: "system-ui, sans-serif", color: "#e6edf3" };
  const input: React.CSSProperties = { padding: "10px 12px", borderRadius: 8, border: "1px solid #2a3441", background: "#0d1117", color: "#e6edf3", fontSize: 14 };
  const btn: React.CSSProperties = { padding: "10px 16px", borderRadius: 8, border: "none", background: "#3b82f6", color: "#fff", fontWeight: 600, cursor: "pointer" };

  if (!authed) {
    return (
      <div style={box}>
        <h1 style={{ fontSize: 24 }}>ARVIO · Panel</h1>
        <p style={{ color: "#8b96a5" }}>Clave de administración</p>
        <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
          <input style={{ ...input, flex: 1 }} type="password" value={key} onChange={(e) => setKey(e.target.value)} placeholder="clave" />
          <button style={btn} onClick={() => load(key)}>Entrar</button>
        </div>
        {err && <p style={{ color: "#ef4444", marginTop: 10 }}>{err}</p>}
      </div>
    );
  }

  return (
    <div style={box}>
      <h1 style={{ fontSize: 24, marginBottom: 4 }}>Servidores Xtream</h1>
      <p style={{ color: "#8b96a5", marginBottom: 20 }}>El login prueba estos servidores (activos, en orden) hasta que uno acepte la cuenta.</p>

      <div style={{ display: "flex", gap: 8, marginBottom: 24, flexWrap: "wrap" }}>
        <input style={{ ...input, flex: "2 1 320px" }} value={url} onChange={(e) => setUrl(e.target.value)} placeholder="http://tu-servidor.com:80" />
        <input style={{ ...input, flex: "1 1 160px" }} value={label} onChange={(e) => setLabel(e.target.value)} placeholder="etiqueta (opcional)" />
        <button style={btn} onClick={add}>Agregar</button>
      </div>
      {err && <p style={{ color: "#ef4444", marginBottom: 12 }}>{err}</p>}

      <div style={{ display: "grid", gap: 8 }}>
        {servers.length === 0 && <p style={{ color: "#8b96a5" }}>Sin servidores. Agrega el primero arriba.</p>}
        {servers.map((s) => (
          <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "#161b22", border: "1px solid #232b36", borderRadius: 10 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "monospace", fontSize: 13, overflow: "hidden", textOverflow: "ellipsis" }}>{s.url}</div>
              {s.label && <div style={{ fontSize: 12, color: "#8b96a5" }}>{s.label}</div>}
            </div>
            <button style={{ ...btn, background: s.active ? "#22c55e" : "#374151", padding: "6px 12px", fontSize: 12 }} onClick={() => patch(s.id, { active: !s.active })}>
              {s.active ? "Activo" : "Inactivo"}
            </button>
            <button style={{ ...btn, background: "#ef4444", padding: "6px 12px", fontSize: 12 }} onClick={() => del(s.id)}>Borrar</button>
          </div>
        ))}
      </div>
    </div>
  );
}
