/* panel-pqrs.jsx — "Mis PQRs": quejas de pedido (con trazabilidad) + PQRs generales */
const { useState: pqState, useEffect: pqEffect } = React;

const PQG_TIPOS = [["peticion", "Petición"], ["queja_general", "Queja general"], ["reclamo", "Reclamo"], ["felicitacion", "Felicitación"]];
const PQ_FECHA = (iso) => iso ? new Date(iso).toLocaleDateString("es-CO", { day: "numeric", month: "short", year: "numeric" }) : "—";

/* Modal: enviar un PQR general (no ligado a un pedido) */
function PQRGeneralModal({ usuario, restId, onClose, onCreated }) {
  const [f, setF] = pqState({ tipo: "peticion", asunto: "", mensaje: "" });
  const [busy, setBusy] = pqState(false);
  const [err, setErr] = pqState("");
  const [ok, setOk] = pqState(false);
  const esFeli = f.tipo === "felicitacion";

  async function enviar() {
    if (busy) return;
    if (!f.asunto.trim() || !f.mensaje.trim()) { setErr("Completa asunto y mensaje."); return; }
    setBusy(true); setErr("");
    const { error } = await window.crearPQR({ usuario_id: usuario ? usuario.id : null, restaurante_id: restId, tipo: f.tipo, asunto: f.asunto, mensaje: f.mensaje });
    setBusy(false);
    if (error) { console.error("[Treego] crearPQR:", error.message); setErr("No se pudo enviar. Intenta de nuevo."); return; }
    setOk(true); onCreated && onCreated();
  }

  return (
    <React.Fragment>
      <div className="drawer-bg" onClick={onClose}></div>
      <div className="an-modal tk-modal">
        <button className="dx" onClick={onClose}><Icon name="plus" style={{ transform: "rotate(45deg)" }} /></button>
        <div className="tk-head">
          <span className="tk-ic" style={esFeli ? { background: "var(--green-bg)", color: "var(--green)" } : {}}><Icon name={esFeli ? "heart" : "bell"} /></span>
          <div><h2>Enviar PQR general</h2><div className="tk-sub">Peticiones, quejas, reclamos y felicitaciones</div></div>
        </div>
        {ok ? (
          <div className="tk-ok">
            <p>{esFeli ? "¡Gracias por tu felicitación!" : "Tu mensaje fue enviado. Te responderemos pronto."}</p>
            <button className="btn btn-primary full" onClick={onClose}>Listo</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="tk-body">
              {err && <p style={{ color: "var(--red)", fontSize: 13.5, margin: "0 0 14px" }}>{err}</p>}
              <div className="tk-grp"><span className="tk-lbl">Tipo</span>
                <select className="tk-select" value={f.tipo} onChange={(e) => setF((p) => ({ ...p, tipo: e.target.value }))}>
                  {PQG_TIPOS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                </select></div>
              <div className="tk-grp"><span className="tk-lbl">Asunto</span>
                <input className="tk-textarea" style={{ minHeight: 0 }} value={f.asunto} onChange={(e) => setF((p) => ({ ...p, asunto: e.target.value }))} placeholder="Resumen breve" /></div>
              <div className="tk-grp"><span className="tk-lbl">Mensaje</span>
                <textarea className="tk-textarea" rows={4} value={f.mensaje} onChange={(e) => setF((p) => ({ ...p, mensaje: e.target.value }))} placeholder={esFeli ? "Escríbenos algo bonito" : "Cuéntanos en detalle"} /></div>
            </div>
            <div className="tk-foot">
              <button className="btn btn-primary full" style={esFeli ? { background: "var(--green)", boxShadow: "none" } : {}} disabled={busy} onClick={enviar}><Icon name={esFeli ? "heart" : "check"} />{busy ? "Enviando…" : "Enviar"}</button>
              <button className="tk-cancel" disabled={busy} onClick={onClose}>Cancelar</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </React.Fragment>
  );
}

function MisPQRsView({ usuario, restId }) {
  const [pqrs, setPqrs] = pqState([]);
  const [cargando, setCargando] = pqState(true);
  const [reportar, setReportar] = pqState(false);
  const [general, setGeneral] = pqState(false);

  const recargar = () => window.cargarMisPQRs().then((d) => { setPqrs(d); setCargando(false); });
  pqEffect(() => { recargar(); }, []);

  return (
    <div className="fade-in">
      <div className="between" style={{ margin: "8px 0 16px" }}>
        <h3 style={{ fontSize: 18 }}>Mis PQRs</h3>
        <div className="row" style={{ gap: 12, alignItems: "center", flexWrap: "wrap" }}>
          <span className="muted" style={{ fontSize: 13 }}>{pqrs.length} en total</span>
          <button className="btn btn-ghost" style={{ padding: "10px 14px" }} onClick={() => setReportar(true)}><Icon name="flag" />Reportar incidencia</button>
          <button className="btn btn-primary" style={{ padding: "10px 14px" }} onClick={() => setGeneral(true)}><Icon name="plus" />Enviar PQR general</button>
        </div>
      </div>

      {reportar && <NuevaReclamacionModal onClose={() => setReportar(false)} onCreated={recargar} />}
      {general && <PQRGeneralModal usuario={usuario} restId={restId} onClose={() => setGeneral(false)} onCreated={recargar} />}

      {cargando && <div className="card" style={{ padding: 28, textAlign: "center", color: "var(--ink-3)" }}>Cargando…</div>}
      {!cargando && pqrs.length === 0 && <div className="card" style={{ padding: 28, textAlign: "center", color: "var(--ink-3)" }}>No has enviado ningún PQR. Usa los botones de arriba.</div>}
      {!cargando && pqrs.map((p) => {
        const ei = window.estadoInfo(p.estado);
        if (window.esTipoPedido(p.tipo) && p.tickets) {
          const t = p.tickets;
          const cod = t.pedidos ? (t.pedidos.codigo_restaurante || t.pedido_id) : t.pedido_id;
          return (
            <div className="tk-card" key={p.id}>
              <div className="tk-card-head">
                <div><div className="tk-ttl">{window.labelTipo("queja_pedido")} · {window.labelIncidencia(t.tipo_incidencia)}</div><span className="muted" style={{ fontSize: 12.5 }}>Pedido #{cod}</span></div>
                <span className={"pill " + ei.pill}>{ei.label}</span>
              </div>
              {t.descripcion && <p className="tk-card-desc">{t.descripcion}</p>}
              <TicketTimeline t={t} />
              {t.estado === "resuelto" && (
                <div className="tk-comp">
                  {t.compensacion_tipo
                    ? <React.Fragment><span className="tk-comp-l">Compensación aplicada · {window.labelComp(t.compensacion_tipo)}</span><span className="tk-comp-v">{t.compensacion_valor != null ? fmtCOP(t.compensacion_valor) : "—"}</span></React.Fragment>
                    : <span className="tk-comp-l">Resuelto sin compensación económica</span>}
                </div>
              )}
            </div>
          );
        }
        return (
          <div className="card card-pad" key={p.id} style={{ marginBottom: 12 }}>
            <div className="between">
              <div><b>{p.asunto || "—"}</b><span className="muted" style={{ fontSize: 12.5, display: "block" }}>{window.labelTipo(p.tipo)} · {PQ_FECHA(p.fecha_creacion)}</span></div>
              <span className={"pill " + ei.pill}>{ei.label}</span>
            </div>
            <p className="muted" style={{ fontSize: 13, margin: "10px 0 0" }}>{p.mensaje}</p>
            {p.respuesta && <div style={{ marginTop: 12, padding: "10px 12px", borderRadius: 10, background: "var(--panel-2)", borderLeft: "3px solid var(--g2)" }}><span className="muted" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>Respuesta de Treego</span><p style={{ fontSize: 13.5, margin: "4px 0 0" }}>{p.respuesta}</p></div>}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { MisPQRsView, PQRGeneralModal });
