/* global React, Icon */
// ============================================================================
// Chantier K.3 · RGPD · Demandes d'effacement (super-admin)
// ----------------------------------------------------------------------------
// Liste toutes les demandes deletion_requests. Super-admin peut approuver
// (anonymisation immédiate) ou refuser (motif requis). RLS impose déjà
// la visibilité — la page elle-même refait un contrôle defensif.
// ============================================================================

const { useState: useStateDR, useEffect: useEffectDR } = React;

function DeletionRequestsScreen({ t, lang, isSuperAdmin }) {
  const { has, loading: permsLoading } = window.melr.useCurrentUserPermissions();
  const [filterStatus, setFilterStatus] = useStateDR("pending");

  const { data: requests, loading, error, refresh } = window.melr.useDeletionRequests
    ? window.melr.useDeletionRequests({ status: filterStatus || undefined })
    : { data: [], loading: false, error: null, refresh: () => {} };

  const [processing, setProcessing] = useStateDR(null);  // request being processed
  const [decision, setDecision]     = useStateDR(null);  // 'approve' | 'reject'
  const [adminNotes, setAdminNotes] = useStateDR("");
  const [busy, setBusy] = useStateDR(false);
  const [err, setErr]   = useStateDR(null);

  if (permsLoading) {
    return <div className="page"><div style={{ padding: 28 }}>{window.L("Chargement…", "Loading…", "Cargando…")}</div></div>;
  }
  const canView = isSuperAdmin || (has && has("orgs.manage"));
  if (!canView) {
    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{window.L("CONFORMITÉ", "COMPLIANCE", "CUMPLIMIENTO")}</div>
          <h1 className="page-title">{window.L("Demandes RGPD", "GDPR requests", "Solicitudes RGPD")}</h1>
        </div>
        <div className="card" style={{ marginTop: 16, padding: 24 }}>
          <div className="text-faint" style={{ textAlign: "center" }}>
            {window.L("Accès réservé aux super-administrateurs.", "Restricted to super-administrators.", "Acceso reservado a los superadministradores.")}
          </div>
        </div>
      </div>
    );
  }

  const T = (fr, en) => (lang === "fr" ? fr : en);

  const openDecision = (req, kind) => {
    setProcessing(req); setDecision(kind); setAdminNotes(""); setErr(null);
  };
  const closeDecision = () => {
    setProcessing(null); setDecision(null); setAdminNotes(""); setErr(null);
  };

  const submitDecision = async () => {
    if (!processing || !decision) return;
    if (decision === "reject" && !adminNotes.trim()) {
      setErr(T("Le motif est requis en cas de refus.", "Reason is required for rejection."));
      return;
    }
    setBusy(true); setErr(null);
    try {
      await window.melr.processDeletionRequest(processing.id, decision, adminNotes.trim() || null);
      closeDecision();
      refresh();
    } catch (e) {
      setErr(e.message || String(e));
    } finally {
      setBusy(false);
    }
  };

  const fmtDate = (iso) => {
    if (!iso) return "—";
    try { return new Date(iso).toLocaleString(window.L("fr-FR", "en-GB", "es-ES")); }
    catch (_) { return iso; }
  };

  const statusChip = (status) => {
    const m = {
      pending:   { fr: "En attente", en: "Pending", es: "Pendiente",   bg: "#fef3c7", color: "#92400e" },
      approved:  { fr: "Approuvée",  en: "Approved", es: "Aprobada",  bg: "#dcfce7", color: "#166534" },
      rejected:  { fr: "Refusée",    en: "Rejected", es: "Rechazada",  bg: "#fee2e2", color: "#991b1b" },
      cancelled: { fr: "Annulée",    en: "Cancelled", es: "Cancelada", bg: "#f1f5f9", color: "#475569" },
    }[status] || { fr: status, en: status, bg: "#f1f5f9", color: "#475569" };
    return (
      <span style={{
        display: "inline-block", padding: "2px 8px", borderRadius: 10,
        background: m.bg, color: m.color, fontSize: 11, fontWeight: 600,
      }}>{T(m.fr, m.en)}</span>
    );
  };

  const pendingCount = (requests || []).filter((r) => r.status === "pending").length;

  return (
    <div className="page" data-screen-label="App / deletion_requests">
      <div className="page-header">
        <div className="page-eyebrow">{window.L("CONFORMITÉ", "COMPLIANCE", "CUMPLIMIENTO")}</div>
        <div className="page-header-row" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <h1 className="page-title">{T("Demandes RGPD", "GDPR requests")}</h1>
          <button className="btn-secondary" onClick={refresh}
            style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px", fontSize: 12 }}>
            {Icon && Icon.refresh ? <Icon.refresh className="sm" /> : "↻"} {T("Rafraîchir", "Refresh")}
          </button>
        </div>
        <div className="page-sub" style={{ fontSize: 13, color: "var(--text-faint)", marginTop: 4 }}>
          {T(
            "Demandes de suppression de compte au titre du droit à l'effacement (RGPD Article 17). L'approbation déclenche une anonymisation irréversible.",
            "Account deletion requests under the right to erasure (GDPR Article 17). Approval triggers an irreversible anonymization."
          )}
        </div>
      </div>

      {/* Filtres */}
      <div className="card" style={{ marginTop: 14, padding: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <label style={{ display: "flex", flexDirection: "column", gap: 4, fontSize: 12, minWidth: 180 }}>
            <span style={{ color: "var(--text-faint)" }}>{T("Statut", "Status")}</span>
            <select value={filterStatus || ""} onChange={(e) => setFilterStatus(e.target.value || null)}>
              <option value="">{T("— Tous —", "— All —")}</option>
              <option value="pending">{T("En attente", "Pending")}</option>
              <option value="approved">{T("Approuvées", "Approved")}</option>
              <option value="rejected">{T("Refusées", "Rejected")}</option>
              <option value="cancelled">{T("Annulées", "Cancelled")}</option>
            </select>
          </label>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "8px 14px", borderRadius: 6, background: "#fef3c7", fontSize: 12.5, color: "#92400e" }}>
            <span style={{ fontWeight: 700, fontSize: 16 }}>{pendingCount}</span>
            {T("demande(s) en attente", "pending request(s)")}
          </div>
        </div>
      </div>

      {/* Tableau */}
      <div className="card" style={{ marginTop: 14 }}>
        <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--border, #e5e7eb)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>
            {loading ? T("Chargement…", "Loading…") : T(`${requests.length} demande(s)`, `${requests.length} request(s)`)}
          </div>
          {error && <div style={{ color: "var(--red, #dc2626)", fontSize: 12 }}>{String(error)}</div>}
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ background: "var(--bg-soft, #f9fafb)", textAlign: "left" }}>
                <th style={thStyleDR}>{T("Statut", "Status")}</th>
                <th style={thStyleDR}>{T("Cible", "Target")}</th>
                <th style={thStyleDR}>{T("Soumise le", "Submitted")}</th>
                <th style={thStyleDR}>{T("Motif", "Reason")}</th>
                <th style={thStyleDR}>{T("Traitement", "Processing")}</th>
                <th style={thStyleDR}></th>
              </tr>
            </thead>
            <tbody>
              {(requests || []).map((r) => (
                <tr key={r.id} style={{ borderTop: "1px solid var(--border-soft, #f1f5f9)" }}>
                  <td style={tdStyleDR}>
                    {statusChip(r.status)}
                    {r.overdue_30d && r.status === "pending" && (
                      <div style={{ marginTop: 4 }}>
                        <span style={{ padding: "1px 6px", borderRadius: 8, background: "#fef2f2", color: "#991b1b", fontSize: 10, fontWeight: 700 }}>
                          {T("> 30j", "> 30d")}
                        </span>
                      </div>
                    )}
                  </td>
                  <td style={tdStyleDR}>
                    <div>{r.target_name_current || r.target_email || "—"}</div>
                    <div style={{ color: "var(--text-faint)", fontSize: 11 }}>
                      {r.target_email_current && r.target_email_current !== r.target_name_current ? r.target_email_current : r.target_email}
                    </div>
                  </td>
                  <td style={tdStyleDR}>
                    <div>{fmtDate(r.requested_at)}</div>
                    <div style={{ color: "var(--text-faint)", fontSize: 11 }}>
                      {T("par", "by")} {r.requester_email || "—"}
                    </div>
                  </td>
                  <td style={tdStyleDR}>
                    <div style={{ fontStyle: r.reason ? "italic" : "normal", color: r.reason ? "#334155" : "var(--text-faint)", fontSize: 12, maxWidth: 240, whiteSpace: "pre-wrap", wordBreak: "break-word" }}>
                      {r.reason || T("(aucun)", "(none)")}
                    </div>
                  </td>
                  <td style={tdStyleDR}>
                    {r.processed_at ? (
                      <div>
                        <div>{fmtDate(r.processed_at)}</div>
                        <div style={{ color: "var(--text-faint)", fontSize: 11 }}>
                          {T("par", "by")} {r.processor_email || "—"}
                        </div>
                        {r.admin_notes && (
                          <div style={{ marginTop: 4, fontSize: 11, color: "#475569" }}>
                            « {r.admin_notes} »
                          </div>
                        )}
                      </div>
                    ) : (
                      <span style={{ color: "var(--text-faint)" }}>—</span>
                    )}
                  </td>
                  <td style={tdStyleDR}>
                    {r.status === "pending" && (
                      <div style={{ display: "flex", gap: 6 }}>
                        <button onClick={() => openDecision(r, "approve")}
                          style={{
                            padding: "4px 10px", borderRadius: 6, border: "1px solid #16a34a",
                            background: "#22c55e", color: "white", cursor: "pointer", fontSize: 11, fontWeight: 600,
                          }}>
                          ✓ {T("Approuver", "Approve")}
                        </button>
                        <button onClick={() => openDecision(r, "reject")}
                          style={{
                            padding: "4px 10px", borderRadius: 6, border: "1px solid #b91c1c",
                            background: "#dc2626", color: "white", cursor: "pointer", fontSize: 11, fontWeight: 600,
                          }}>
                          ✕ {T("Refuser", "Reject")}
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
              {!loading && (!requests || requests.length === 0) && (
                <tr><td colSpan={6} style={{ padding: 28, textAlign: "center", color: "var(--text-faint)" }}>
                  {T("Aucune demande pour ce filtre.", "No request for this filter.")}
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal de confirmation Approve/Reject */}
      {processing && decision && (
        <div style={{
          position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
          display: "flex", alignItems: "center", justifyContent: "center",
          zIndex: 1000, padding: 20,
        }} onClick={() => !busy && closeDecision()}>
          <div style={{
            background: "white", borderRadius: 10, maxWidth: 560, width: "100%",
            padding: 24, boxShadow: "0 20px 50px rgba(0,0,0,0.25)",
          }} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ margin: 0, marginBottom: 12, fontSize: 17, color: decision === "approve" ? "#166534" : "#7f1d1d" }}>
              {decision === "approve"
                ? T("✓ Approuver la demande de suppression", "✓ Approve deletion request")
                : T("✕ Refuser la demande de suppression", "✕ Reject deletion request")}
            </h3>
            <div style={{ fontSize: 12.5, color: "#475569", marginBottom: 14, lineHeight: 1.6 }}>
              <div><strong>{T("Cible :", "Target:")}</strong> {processing.target_email_current || processing.target_email}</div>
              <div><strong>{T("Soumise le :", "Submitted:")}</strong> {fmtDate(processing.requested_at)}</div>
              {processing.reason && (
                <div style={{ marginTop: 6, fontStyle: "italic" }}>« {processing.reason} »</div>
              )}
            </div>
            {decision === "approve" && (
              <div style={{
                padding: 10, marginBottom: 14, borderRadius: 6,
                background: "#fef2f2", border: "1px solid #fca5a5", color: "#7f1d1d", fontSize: 12,
              }}>
                {T(
                  "⚠ Action irréversible. Le profil sera anonymisé immédiatement : email + nom remplacés, memberships supprimés, accès auth révoqué. Les données métier (indicateurs, activités) sont conservées sans lien à l'identité.",
                  "⚠ Irreversible action. The profile will be anonymized immediately: email + name replaced, memberships dropped, auth access revoked. Business data (indicators, activities) is preserved without identity link."
                )}
              </div>
            )}
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>
              {decision === "reject"
                ? T("Motif de refus (requis)", "Rejection reason (required)")
                : T("Note interne (facultative)", "Internal note (optional)")}
            </label>
            <textarea value={adminNotes} onChange={(e) => setAdminNotes(e.target.value)}
              rows={3} maxLength={500}
              style={{
                width: "100%", boxSizing: "border-box",
                padding: 8, borderRadius: 6, border: "1px solid #cbd5e1",
                fontFamily: "inherit", fontSize: 12.5, resize: "vertical",
              }} />
            {err && (
              <div style={{
                marginTop: 10, padding: 8, borderRadius: 6,
                background: "#fee2e2", border: "1px solid #fca5a5", color: "#7f1d1d", fontSize: 12,
              }}>{err}</div>
            )}
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 16 }}>
              <button onClick={closeDecision} disabled={busy}
                style={{
                  padding: "8px 14px", borderRadius: 6, border: "1px solid #94a3b8",
                  background: "white", color: "#334155", cursor: busy ? "default" : "pointer", fontSize: 13,
                }}>
                {T("Annuler", "Cancel")}
              </button>
              <button onClick={submitDecision} disabled={busy}
                style={{
                  padding: "8px 14px", borderRadius: 6,
                  border: "1px solid " + (decision === "approve" ? "#16a34a" : "#b91c1c"),
                  background: busy ? "#cbd5e1" : (decision === "approve" ? "#22c55e" : "#dc2626"),
                  color: "white", cursor: busy ? "default" : "pointer", fontWeight: 600, fontSize: 13,
                }}>
                {busy ? T("Traitement…", "Processing…") : (decision === "approve" ? T("Confirmer l'approbation", "Confirm approval") : T("Confirmer le refus", "Confirm rejection"))}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

const thStyleDR = {
  padding: "8px 12px",
  fontSize: 11,
  fontWeight: 600,
  color: "var(--text-faint)",
  textTransform: "uppercase",
  letterSpacing: 0.4,
};
const tdStyleDR = {
  padding: "10px 12px",
  fontSize: 13,
  verticalAlign: "top",
};

window.DeletionRequestsScreen = DeletionRequestsScreen;
