// settings-modal.jsx — Modal unificado de Configuración del admin.
// Pestañas: "WhatsApp" (número admin) y "Contraseña" (cambio de password).

const CC = "57"; // Colombia — código de país que se antepone automáticamente

// Quita "57" inicial si viene del backend ya con prefijo.
function stripCountry(raw) {
  const digits = (raw || "").replace(/\D+/g, "");
  if (digits.startsWith(CC) && digits.length === CC.length + 10) {
    return digits.slice(CC.length);
  }
  return digits;
}

// ════════════════════════════════════════════════════════════════════
// Sección WhatsApp
// ════════════════════════════════════════════════════════════════════
function WhatsAppSection({ onSuccess, onError, onClose }) {
  const [phone, setPhone]     = React.useState("");
  const [notify, setNotify]   = React.useState(true);
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving]   = React.useState(false);
  const [error, setError]     = React.useState(null);
  const [waha, setWaha]       = React.useState(null);

  React.useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const [p, n] = await Promise.all([
          api.getAdminPhone(),
          api.getAdminNotify(),
        ]);
        if (alive) {
          setPhone(stripCountry(p));
          setNotify(n);
        }
      } catch (err) {
        if (alive) setError((err && err.message) || "No se pudo cargar la configuración");
      } finally {
        if (alive) setLoading(false);
      }
    })();
    // Estado de WAHA en vivo: consulta al abrir y luego cada 10s, para que
    // si se elimina/cae el número conectado, el indicador cambie solo.
    const fetchWaha = async () => {
      try {
        const w = await api.getWahaNumber();
        if (alive) setWaha(w);
      } catch (_) { /* informativo, no bloquea el formulario */ }
    };
    fetchWaha();
    const poll = setInterval(fetchWaha, 10000);
    return () => { alive = false; clearInterval(poll); };
  }, []);

  const handlePhoneChange = (e) => {
    setPhone((e.target.value || "").replace(/\D+/g, "").slice(0, 10));
    setError(null);
  };

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (phone.length !== 10) return setError("El celular debe tener 10 dígitos.");
    if (phone[0] !== "3")    return setError("Un celular colombiano debe empezar por 3.");

    setSaving(true);
    try {
      await api.updateAdminPhone(CC + phone);
      await api.updateAdminNotify(notify);
      onSuccess && onSuccess("Configuración de WhatsApp actualizada");
      onClose();
    } catch (err) {
      setError((err && err.message) || "No se pudo guardar la configuración");
      onError && onError(err);
    } finally {
      setSaving(false);
    }
  };

  const preview = (() => {
    if (!phone) return `+${CC} ___ ___ ____`;
    const a = phone.slice(0, 3).padEnd(3, "_");
    const b = phone.slice(3, 6).padEnd(3, "_");
    const c = phone.slice(6, 10).padEnd(4, "_");
    return `+${CC} ${a} ${b} ${c}`;
  })();

  return (
    <form onSubmit={submit} autoComplete="off">
      <div className="field" style={{ marginBottom: 10 }}>
        <label className="field-label" htmlFor="cfg-phone">
          Número de WhatsApp del admin
        </label>
        <div style={{ position: "relative" }}>
          <span
            aria-hidden="true"
            style={{
              position: "absolute", top: "50%", left: 12,
              transform: "translateY(-50%)",
              color: "var(--ink-2)", fontWeight: 600,
              pointerEvents: "none",
              fontFamily: "var(--font-mono, ui-monospace, monospace)",
              fontSize: 13.5,
            }}
          >+{CC}</span>
          <input
            id="cfg-phone"
            className="input"
            type="tel"
            inputMode="numeric"
            autoComplete="off"
            placeholder={loading ? "Cargando…" : ""}
            value={phone}
            onChange={handlePhoneChange}
            disabled={loading || saving}
            required
            minLength={10}
            maxLength={10}
            style={{ paddingLeft: 48 }}
          />
        </div>
      </div>

      <div
        style={{
          fontSize: 12, color: "var(--ink-3)", marginBottom: 4,
          fontFamily: "var(--font-mono, ui-monospace, monospace)",
        }}
      >
        Vista previa: <b style={{ color: "var(--ink-1)" }}>{preview}</b>
      </div>

      <label
        className="cfg-toggle"
        style={{
          marginTop: 14,
          display: "flex", alignItems: "center", gap: 10,
          padding: "10px 12px",
          background: "var(--bg-1, rgba(255,255,255,.03))",
          border: "1px solid var(--border)",
          borderRadius: "var(--radius-sm)",
          cursor: loading || saving ? "default" : "pointer",
          userSelect: "none",
        }}
      >
        <input
          type="checkbox"
          checked={notify}
          onChange={e => setNotify(e.target.checked)}
          disabled={loading || saving}
          style={{ width: 18, height: 18, flexShrink: 0, accentColor: "var(--accent, #2563eb)" }}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, color: "var(--ink-1)", fontWeight: 600 }}>
            Recibir aviso por WhatsApp al crear un ticket
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>
            Si está apagado, el admin no recibe WhatsApp personal (los grupos de proyecto sí siguen funcionando).
          </div>
        </div>
      </label>

      {(() => {
        const checking = waha == null;
        const online   = waha && waha.ok && waha.connected && waha.phone;
        const dotColor = checking ? "var(--ink-3)" : online ? "var(--done, #10b981)" : "var(--p-high, #e11d48)";
        return (
          <div
            style={{
              marginTop: 14, padding: "10px 12px",
              background: "var(--bg-1, rgba(255,255,255,.03))",
              border: "1px solid var(--border)",
              borderRadius: "var(--radius-sm)", fontSize: 12.5,
              color: "var(--ink-2)",
            }}
          >
            <div style={{ marginBottom: 6, color: "var(--ink-3)" }}>
              WhatsApp que envía los mensajes (WAHA)
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span
                aria-hidden="true"
                style={{
                  width: 9, height: 9, borderRadius: 999, flexShrink: 0,
                  background: dotColor,
                  boxShadow: online ? "0 0 0 3px color-mix(in oklab, var(--done, #10b981) 25%, transparent)" : "none",
                }}
              />
              {checking
                ? <span style={{ color: "var(--ink-3)" }}>Consultando…</span>
                : online
                  ? <span>
                      <b style={{ color: "var(--done, #10b981)" }}>En línea</b>{" · "}
                      <b style={{ color: "var(--ink-1)", fontFamily: "var(--font-mono, monospace)" }}>
                        +{waha.phone}{waha.name ? ` · ${waha.name}` : ""}
                      </b>
                    </span>
                  : <span style={{ color: "var(--p-high, #e11d48)", fontWeight: 600 }}>
                      Sin conexión — ningún número vinculado
                    </span>}
            </div>
          </div>
        );
      })()}

      {error && <AlertBox text={error} />}

      <ModalFooter>
        <button type="button" className="btn btn-sm" onClick={onClose} disabled={saving}>
          Cancelar
        </button>
        <button
          type="submit"
          className="btn btn-sm btn-primary"
          disabled={saving || loading || phone.length !== 10}
        >
          <Icon name="check" style={{ width: 13, height: 13 }} />
          {saving ? "Guardando…" : "Guardar"}
        </button>
      </ModalFooter>
    </form>
  );
}

// ════════════════════════════════════════════════════════════════════
// Sección Contraseña
// ════════════════════════════════════════════════════════════════════
function PasswordSection({ onSuccess, onError, onClose }) {
  const [current, setCurrent] = React.useState("");
  const [next, setNext]       = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [saving, setSaving]   = React.useState(false);
  const [error, setError]     = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);

    if (next.length < 8)     return setError("La nueva contraseña debe tener al menos 8 caracteres.");
    if (next !== confirm)    return setError("La confirmación no coincide con la nueva contraseña.");
    if (current === next)    return setError("La nueva contraseña debe ser distinta a la actual.");

    setSaving(true);
    try {
      await api.changePassword(current, next);
      onSuccess && onSuccess("Contraseña actualizada correctamente");
      onClose();
    } catch (err) {
      setError((err && err.message) || "No se pudo cambiar la contraseña");
      onError && onError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={submit} autoComplete="off">
      <PwInput id="pw-current"  label="Contraseña actual"           value={current} onChange={e => setCurrent(e.target.value)} />
      <PwInput id="pw-new"      label="Nueva contraseña"            value={next}    onChange={e => setNext(e.target.value)}    placeholder="Mínimo 8 caracteres" />
      <PwInput id="pw-confirm"  label="Confirmar nueva contraseña"  value={confirm} onChange={e => setConfirm(e.target.value)} />

      {error && <AlertBox text={error} />}

      <ModalFooter>
        <button type="button" className="btn btn-sm" onClick={onClose} disabled={saving}>
          Cancelar
        </button>
        <button
          type="submit"
          className="btn btn-sm btn-primary"
          disabled={saving || !current || !next || !confirm}
        >
          <Icon name="check" style={{ width: 13, height: 13 }} />
          {saving ? "Guardando…" : "Guardar"}
        </button>
      </ModalFooter>
    </form>
  );
}

// ════════════════════════════════════════════════════════════════════
// Helpers compartidos
// ════════════════════════════════════════════════════════════════════
function AlertBox({ text }) {
  return (
    <div
      style={{
        marginTop: 14,
        padding: "10px 12px",
        background: "var(--p-high-soft, rgba(225,29,72,.12))",
        border: "1px solid color-mix(in oklab, var(--p-high, #e11d48) 30%, transparent)",
        borderRadius: "var(--radius-sm)",
        color: "var(--p-high, #e11d48)",
        fontSize: 13,
        fontWeight: 600,
      }}
    >
      {text}
    </div>
  );
}

function ModalFooter({ children }) {
  return (
    <div className="modal-foot" style={{ paddingLeft: 0, paddingRight: 0, marginTop: 18 }}>
      <div className="left" />
      <div className="right">{children}</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// Modal con tabs
// ════════════════════════════════════════════════════════════════════
function SettingsModal({ onClose, onSuccess, onError }) {
  const [tab, setTab] = React.useState("whatsapp");

  React.useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  const onBackClick = (e) => { if (e.target === e.currentTarget) onClose(); };

  const tabStyle = (active) => ({
    flex: 1,
    padding: "10px 14px",
    background: active ? "var(--Panel, rgba(255,255,255,.04))" : "transparent",
    border: "none",
    borderBottom: active ? "2px solid var(--primary, #6366f1)" : "2px solid transparent",
    color: active ? "var(--ink-1)" : "var(--ink-2)",
    fontWeight: active ? 700 : 500,
    fontSize: 13.5,
    cursor: "pointer",
    transition: "all .15s ease",
    display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
  });

  return (
    <div className="modal-back" onMouseDown={onBackClick}>
      <div
        className="modal"
        onMouseDown={e => e.stopPropagation()}
        style={{ maxWidth: 480 }}
      >
        <div className="modal-h">
          <Icon name="bell" style={{ width: 18, height: 18 }} />
          <h2 style={{ margin: 0 }}>Configuración</h2>
          <button className="modal-x" onClick={onClose} aria-label="Cerrar">
            <Icon name="x" />
          </button>
        </div>

        {/* Tabs */}
        <div
          role="tablist"
          style={{
            display: "flex",
            borderBottom: "1px solid var(--border)",
            margin: "0 -20px",
          }}
        >
          <button
            type="button"
            role="tab"
            aria-selected={tab === "whatsapp"}
            onClick={() => setTab("whatsapp")}
            style={tabStyle(tab === "whatsapp")}
          >
            <Icon name="whatsapp" style={{ width: 15, height: 15 }} />
            WhatsApp
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={tab === "password"}
            onClick={() => setTab("password")}
            style={tabStyle(tab === "password")}
          >
            <Icon name="lock" style={{ width: 14, height: 14 }} />
            Contraseña
          </button>
        </div>

        <div className="modal-body">
          {tab === "whatsapp" && (
            <WhatsAppSection
              onClose={onClose}
              onSuccess={onSuccess}
              onError={onError}
            />
          )}
          {tab === "password" && (
            <PasswordSection
              onClose={onClose}
              onSuccess={onSuccess}
              onError={onError}
            />
          )}
        </div>
      </div>
    </div>
  );
}

window.SettingsModal = SettingsModal;
