import { useState, useEffect, useRef } from "react";
import { api } from "../lib/api";

// Desplegable con búsqueda (estilo Claude).
function ProgramaSelect({ valor, opciones = [], onSelect }) {
  const [abierto, setAbierto] = useState(false);
  const [q, setQ] = useState("");
  const ref = useRef(null);

  useEffect(() => {
    function fuera(e) { if (ref.current && !ref.current.contains(e.target)) setAbierto(false); }
    document.addEventListener("mousedown", fuera);
    return () => document.removeEventListener("mousedown", fuera);
  }, []);

  const filtradas = opciones.filter((o) => o.label.toLowerCase().includes(q.toLowerCase()));

  return (
    <div ref={ref} style={{ position: "relative", width: "100%" }}>
      <button onClick={() => setAbierto((v) => !v)}
        style={{ width: "100%", textAlign: "left", padding: "7px 10px", border: "1px solid #cbd5e1",
                 borderRadius: 8, fontSize: 13, background: "#fff", cursor: "pointer",
                 color: valor ? "#334155" : "#94a3b8", fontFamily: "inherit",
                 display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {valor || "Seleccionar programa..."}
        </span>
        <span style={{ color: "#94a3b8", marginLeft: 6 }}>⌄</span>
      </button>
      {abierto && (
        <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, background: "#fff",
                      border: "1px solid #e2e8f0", borderRadius: 12, boxShadow: "0 12px 34px rgba(0,0,0,0.18)",
                      zIndex: 100, overflow: "hidden" }}>
          <div style={{ padding: 10, borderBottom: "1px solid #f1f5f9" }}>
            <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar..."
              style={{ width: "100%", padding: "8px 11px", border: "1px solid #cbd5e1", borderRadius: 8,
                       fontSize: 13, fontFamily: "inherit", outline: "none" }} />
          </div>
          <div style={{ maxHeight: 220, overflow: "auto" }}>
            {filtradas.length === 0 ? (
              <div style={{ padding: "12px 14px", fontSize: 13, color: "#94a3b8" }}>Sin opciones</div>
            ) : filtradas.map((o) => (
              <div key={o.num_indice} style={{ padding: "9px 14px", fontSize: 13, color: "#334155", cursor: "pointer" }}
                onMouseEnter={(e) => e.currentTarget.style.background = "#f1f5f9"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => { onSelect && onSelect(o); setAbierto(false); setQ(""); }}>
                {o.label}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// Apartado "Programas": lista de programas con contar=NO (ocultos), con switch para reactivar.
function ProgramasOcultos() {
  const [filas, setFilas] = useState([]);
  const [cargando, setCargando] = useState(true);
  const [enc, setEnc] = useState({});   // num_indice -> true si se va a encender
  const [guardando, setGuardando] = useState(false);
  const [msg, setMsg] = useState("");

  useEffect(() => {
    api.programasOcultos()
      .then((r) => { setFilas(r.filas || []); setCargando(false); })
      .catch(() => setCargando(false));
  }, []);

  async function guardar() {
    const nis = Object.entries(enc).filter(([, v]) => v).map(([ni]) => ni);
    if (nis.length === 0) { setMsg("No hay programas para activar."); return; }
    setGuardando(true); setMsg("");
    try {
      await api.encenderProgramas(nis);
      setMsg("✓ Activados. Ya aparecen en la matriz.");
      const r = await api.programasOcultos();
      setFilas(r.filas || []); setEnc({});
    } catch (e) { setMsg("Error: " + e.message); }
    finally { setGuardando(false); }
  }

  return (
    <>
      <div style={{ padding: "16px 22px 6px" }}>
        <div style={{ fontSize: 13, color: "#64748b", lineHeight: 1.5 }}>
          Aquí están los programas ocultos del <b>Detalle por Curso</b>. Enciende el interruptor
          y guarda para que vuelvan a aparecer en la tabla del dashboard.
        </div>
      </div>
      <div style={{ flex: 1, overflow: "auto", padding: "8px 22px" }}>
        {cargando ? (
          <div style={{ padding: 40, textAlign: "center", color: "#94a3b8" }}>Cargando...</div>
        ) : filas.length === 0 ? (
          <div style={{ padding: 30, textAlign: "center", color: "#94a3b8", fontSize: 13 }}>
            No hay programas ocultos.
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {filas.map((f) => {
              const on = !!enc[f.num_indice];
              return (
                <div key={f.num_indice} style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                       padding: "12px 14px", border: "1px solid #e2e8f0", borderRadius: 10, background: "#fff" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#0f172a" }}>{f.dsc_det_programa}</div>
                    <div style={{ fontSize: 12, color: "#94a3b8" }}>
                      Índice {f.num_indice}{f.fch_inicio ? ` · ${f.fch_inicio}` : ""}{f.pauta ? ` · Pauta ${f.pauta}` : ""}
                    </div>
                  </div>
                  <div onClick={() => setEnc((p) => ({ ...p, [f.num_indice]: !p[f.num_indice] }))}
                    style={{ width: 46, height: 26, borderRadius: 999, cursor: "pointer", flexShrink: 0,
                             background: on ? "#2563eb" : "#cbd5e1", position: "relative", transition: "background .15s" }}>
                    <div style={{ width: 20, height: 20, borderRadius: "50%", background: "#fff",
                                  position: "absolute", top: 3, left: on ? 23 : 3, transition: "left .15s",
                                  boxShadow: "0 1px 3px rgba(0,0,0,0.3)" }} />
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                    padding: "14px 22px", borderTop: "1px solid #e2e8f0" }}>
        <span style={{ fontSize: 13, color: msg.startsWith("✓") ? "#047857" : "#b91c1c" }}>{msg}</span>
        <button onClick={guardar} disabled={guardando}
          style={{ padding: "9px 22px", border: "none", background: "#1e3a5f", color: "#fff",
                   borderRadius: 9, fontSize: 14, fontWeight: 700, cursor: guardando ? "wait" : "pointer" }}>
          {guardando ? "Guardando..." : "Guardar"}
        </button>
      </div>
    </>
  );
}

export default function ConfigModal({ onClose }) {
  const [seccion, setSeccion] = useState("leyenda");
  const [filas, setFilas] = useState([]);
  const [cargando, setCargando] = useState(true);
  const [guardando, setGuardando] = useState(false);
  const [msg, setMsg] = useState("");
  const [busca, setBusca] = useState("");
  const [edit, setEdit] = useState({});      // conjunto -> pauta editada
  const [editProg, setEditProg] = useState({}); // conjunto -> {num_indice, label} programa elegido
  const [progOpc, setProgOpc] = useState([]);  // opciones del desplegable de Programa

  useEffect(() => {
    api.leyendaAnuncios()
      .then((r) => { setFilas(r.filas || []); setCargando(false); })
      .catch(() => setCargando(false));
    api.programasDisponibles()
      .then((r) => setProgOpc(r.programas || []))
      .catch(() => setProgOpc([]));
  }, []);

  const setPauta = (conjunto, val) => setEdit((p) => ({ ...p, [conjunto]: val }));
  const valorPauta = (f) => (edit[f.conjunto] !== undefined ? edit[f.conjunto] : (f.pauta || ""));
  // Programa mostrado: el elegido si hay, si no el que ya trae la fila
  const valorPrograma = (f) => (editProg[f.conjunto] !== undefined ? editProg[f.conjunto].label : (f.programa || ""));

  async function guardar() {
    // Un cambio por conjunto que tenga pauta editada o programa elegido
    const conjuntos = new Set([...Object.keys(edit), ...Object.keys(editProg)]);
    const cambios = [];
    for (const conjunto of conjuntos) {
      const f = filas.find((x) => x.conjunto === conjunto) || {};
      const pauta = (edit[conjunto] !== undefined ? edit[conjunto] : (f.pauta || "")).trim();
      const prog = editProg[conjunto];   // {num_indice, label} o undefined
      cambios.push({ conjunto, pauta, num_indice: prog ? prog.num_indice : null });
    }
    if (cambios.length === 0) { setMsg("No hay cambios."); return; }
    setGuardando(true); setMsg("");
    try {
      await api.guardarLeyenda(cambios);
      setMsg("✓ Guardado correctamente.");
      const r = await api.leyendaAnuncios();
      setFilas(r.filas || []); setEdit({}); setEditProg({});
    } catch (e) { setMsg("Error: " + e.message); }
    finally { setGuardando(false); }
  }

  // Orden: 1) pauta Y programa, 2) pauta sin programa, 3) programa sin pauta, 4) nada
  const _rango = (f) => {
    const p = valorPauta(f).trim() !== "";
    const g = (f.programa || "").trim() !== "";
    if (p && g) return 0;
    if (p && !g) return 1;
    if (!p && g) return 2;
    return 3;
  };
  const filtradas = filas
    .filter((f) =>
      !busca || f.conjunto.toLowerCase().includes(busca.toLowerCase())
      || String(f.pauta).includes(busca)
      || (f.programa || "").toLowerCase().includes(busca.toLowerCase()))
    .sort((a, b) => (_rango(a) - _rango(b)) || a.conjunto.localeCompare(b.conjunto));

  return (
    <div onClick={onClose}
      style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
               display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1200 }}>
      <div onClick={(e) => e.stopPropagation()}
        style={{ background: "#fff", borderRadius: 16, width: 1180, maxWidth: "96vw",
                 height: 680, maxHeight: "92vh", display: "flex", overflow: "hidden",
                 boxShadow: "0 24px 70px rgba(0,0,0,0.4)",
                 fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif" }}>
        {/* Sidebar del modal */}
        <div style={{ width: 240, background: "#f8fafc", borderRight: "1px solid #e2e8f0", padding: "18px 12px" }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase",
                        padding: "0 10px 10px" }}>Configuración</div>
          <button onClick={() => setSeccion("leyenda")}
            style={{ width: "100%", textAlign: "left", padding: "10px 12px", borderRadius: 8,
                     border: "none", cursor: "pointer", fontSize: 14, fontWeight: 600, marginBottom: 4,
                     background: seccion === "leyenda" ? "#e2e8f0" : "transparent", color: "#1e293b" }}>
            Leyenda de Anuncios
          </button>
          <button onClick={() => setSeccion("programas")}
            style={{ width: "100%", textAlign: "left", padding: "10px 12px", borderRadius: 8,
                     border: "none", cursor: "pointer", fontSize: 14, fontWeight: 600,
                     background: seccion === "programas" ? "#e2e8f0" : "transparent", color: "#1e293b" }}>
            Programas
          </button>
        </div>
        {/* Contenido */}
        <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                        padding: "16px 22px", borderBottom: "1px solid #e2e8f0" }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: "#0f172a" }}>
              {seccion === "leyenda" ? "Leyenda de Anuncios" : "Programas"}
            </div>
            <button onClick={onClose}
              style={{ background: "transparent", border: "none", fontSize: 24, cursor: "pointer", color: "#64748b" }}>×</button>
          </div>

          {seccion === "programas" ? (
            <ProgramasOcultos />
          ) : (
          <>
          <div style={{ padding: "14px 22px 8px" }}>
            <input value={busca} onChange={(e) => setBusca(e.target.value)}
              placeholder="Buscar conjunto, pauta o programa..."
              style={{ width: "100%", padding: "9px 12px", border: "1px solid #cbd5e1",
                       borderRadius: 9, fontSize: 13 }} />
          </div>

          <div style={{ flex: 1, overflow: "hidden", padding: "0 22px 4px" }}>
            {cargando ? (
              <div style={{ padding: 40, textAlign: "center", color: "#94a3b8" }}>Cargando...</div>
            ) : (
              <div style={{ height: "100%", border: "1px solid #e2e8f0", borderRadius: 12,
                            overflow: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "separate", borderSpacing: 0,
                                tableLayout: "fixed" }}>
                  <colgroup>
                    <col style={{ width: "38%" }} />
                    <col style={{ width: 100 }} />
                    <col style={{ width: "auto" }} />
                  </colgroup>
                  <thead>
                    <tr>
                      <th style={{ position: "sticky", top: 0, zIndex: 20, background: "#1e3a5f", color: "#fff",
                                   padding: "11px 14px", fontSize: 13, fontWeight: 600, textAlign: "left",
                                   borderTopLeftRadius: 12 }}>Conjunto de Anuncios</th>
                      <th style={{ position: "sticky", top: 0, zIndex: 20, background: "#1e3a5f", color: "#fff",
                                   padding: "11px 14px", fontSize: 13, fontWeight: 600, width: 110, textAlign: "left" }}>Pauta</th>
                      <th style={{ position: "sticky", top: 0, zIndex: 20, background: "#1e3a5f", color: "#fff",
                                   padding: "11px 14px", fontSize: 13, fontWeight: 600, textAlign: "left", width: 340,
                                   borderTopRightRadius: 12 }}>Programa</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtradas.map((f) => (
                      <tr key={f.conjunto} style={{ borderBottom: "1px solid #f1f5f9" }}>
                        <td style={{ padding: "8px 14px", fontSize: 13, color: "#334155", textAlign: "left",
                                     borderBottom: "1px solid #f1f5f9", wordBreak: "break-word" }}>{f.conjunto}</td>
                        <td style={{ padding: "8px 14px", borderBottom: "1px solid #f1f5f9" }}>
                          <input value={valorPauta(f)} onChange={(e) => setPauta(f.conjunto, e.target.value)}
                            style={{ width: 90, padding: "6px 8px", border: "1px solid #cbd5e1",
                                     borderRadius: 6, fontSize: 13, textAlign: "left", fontFamily: "inherit",
                                     background: edit[f.conjunto] !== undefined ? "#fffbeb" : "#fff" }} />
                        </td>
                        <td style={{ padding: "8px 14px", borderBottom: "1px solid #f1f5f9",
                                     maxWidth: 0, position: "relative" }}>
                          <ProgramaSelect valor={valorPrograma(f)} opciones={progOpc}
                            onSelect={(o) => setEditProg((p) => ({ ...p, [f.conjunto]: o }))} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                        padding: "14px 22px", borderTop: "1px solid #e2e8f0" }}>
            <span style={{ fontSize: 13, color: msg.startsWith("✓") ? "#047857" : "#b91c1c" }}>{msg}</span>
            <button onClick={guardar} disabled={guardando}
              style={{ padding: "9px 22px", border: "none", background: "#1e3a5f", color: "#fff",
                       borderRadius: 9, fontSize: 14, fontWeight: 700, cursor: guardando ? "wait" : "pointer" }}>
              {guardando ? "Guardando..." : "Guardar"}
            </button>
          </div>
          </>
          )}
        </div>
      </div>
    </div>
  );
}
