// RUT241 eSIM Auto Provisioning — router detail page (spec §41-42, 44,
// 51). Device info, connectivity/job status, config, eSIM, actions
// (gated per-permission — a production_admin sees far fewer buttons
// than a technical_admin, who sees fewer than a super_admin), full
// event log, and SOLO AI Diagnostics (spec §22/§44).
//
// Reuses SectionLabel/EmptyNote/MiniField/ActionButton/ModalShell/
// ModalError/adminInputStyle from admin-assets-page.jsx, AdminShell from
// admin-shell.jsx, RUT241_REGION_LABELS from admin-rut241-dashboard-page.jsx,
// and Rut241StatusPill from admin-rut241-fleet-page.jsx — must load
// after all of those.

function AdminRut241RouterDetailPage({ onNavigate, routerId }) {
  const [admin, setAdmin] = useState(null);
  const [permissions, setPermissions] = useState([]);
  const [status, setStatus] = useState("loading");
  const [device, setDevice] = useState(null);
  const [job, setJob] = useState(null);
  const [events, setEvents] = useState([]);
  const [esim, setEsim] = useState(null);
  const [error, setError] = useState("");
  const [actionBusy, setActionBusy] = useState("");
  const [showRegionModal, setShowRegionModal] = useState(false);
  const [showDiagnostics, setShowDiagnostics] = useState(false);
  const [showLogs, setShowLogs] = useState(false);

  const load = () => {
    if (!routerId) { onNavigate("admin-rut241-fleet"); return; }
    Promise.all([
      fetch("/api/admin/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch("/api/admin/rut241/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch(`/api/admin/rut241/routers/${routerId}`, { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, rut241Me, detail]) => {
        setAdmin(me.admin);
        setPermissions(rut241Me.permissions);
        setDevice(detail.device);
        setJob(detail.job);
        setEvents(detail.events || []);
        setEsim(detail.esim);
        setStatus("ready");
      })
      .catch(() => onNavigate("admin-login"));
  };

  useEffect(load, [routerId]); // eslint-disable-line react-hooks/exhaustive-deps

  const has = (p) => permissions.includes(p);

  const callAction = async (path, method = "POST", body) => {
    setActionBusy(path);
    setError("");
    try {
      const res = await fetch(`/api/admin/rut241/routers/${routerId}${path}`, {
        method, credentials: "same-origin",
        headers: body ? { "Content-Type": "application/json" } : undefined,
        body: body ? JSON.stringify(body) : undefined,
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setError(data.error || "That action failed."); return false; }
      load();
      return true;
    } catch {
      setError("Couldn't reach the server. Check your connection and try again.");
      return false;
    } finally {
      setActionBusy("");
    }
  };

  if (status === "loading" || !device) {
    return <section style={{ background: "#fff", minHeight: "calc(100vh - 88px)" }} />;
  }

  const wanUsed = job && job.wan_used;
  const wanRemovalPending = wanUsed && !job.wan_removed_at;
  const isReady = device.provisioning_status === "READY";

  return (
    <AdminShell admin={admin} page="admin-rut241-dashboard" onNavigate={onNavigate}
      subtitle="RUT241 eSIM Auto Provisioning" title={device.serial_number}
      actions={<ActionButton onClick={() => onNavigate("admin-rut241-fleet")} testId="rut241-back-to-fleet">Back to fleet</ActionButton>}
    >
      {error && <ModalError>{error}</ModalError>}

      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 28, flexWrap: "wrap" }}>
        <Rut241StatusPill status={device.provisioning_status} />
        <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "rgba(0,0,0,0.55)" }}>
          {RUT241_REGION_LABELS[device.deployment_region] || device.deployment_region || "Region not set"}
        </span>
        {job && (
          <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "rgba(0,0,0,0.55)" }}>
            · Connection: {job.current_connection_method === "ESIM_BOOTSTRAP" ? "eSIM bootstrap" : "WAN Ethernet"}
            {job.original_connection_method !== job.current_connection_method && ` (originally ${job.original_connection_method === "ESIM_BOOTSTRAP" ? "eSIM bootstrap" : "WAN Ethernet"})`}
          </span>
        )}
      </div>

      {wanRemovalPending && has("reprovision") && (
        <div style={{ background: "rgba(180,120,0,0.08)", border: "1px solid rgba(180,120,0,0.4)", padding: "16px 18px", marginBottom: 28 }}>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "#7a5300", lineHeight: 1.6, marginBottom: 10 }}>
            This job used WAN Ethernet for initial connection. Before this router can be marked Ready, the WAN cable must be physically removed and mobile-only connectivity confirmed.
          </div>
          <ActionButton onClick={() => callAction("/confirm-wan-removed")} disabled={actionBusy === "/confirm-wan-removed"} testId="rut241-confirm-wan-removed">
            {actionBusy === "/confirm-wan-removed" ? "Confirming…" : "Confirm WAN cable removed"}
          </ActionButton>
        </div>
      )}

      <div style={{ display: "flex", gap: 40, flexWrap: "wrap" }}>
        <div style={{ flex: "1 1 360px" }}>
          <SectionLabel>Device</SectionLabel>
          <Rut241DetailRow label="Model" value={device.model} />
          <Rut241DetailRow label="Product code" value={device.product_code} />
          <Rut241DetailRow label="Hardware revision" value={device.hardware_revision} />
          <Rut241DetailRow label="Serial" value={device.serial_number} />
          <Rut241DetailRow label="IMEI" value={device.imei} />
          <Rut241DetailRow label="LAN MAC" value={device.lan_mac} />
          <Rut241DetailRow label="WiFi MAC" value={device.wifi_mac} />
          {has("view_credentials") && <Rut241DetailRow label="Admin username" value={device.admin_username} />}
          <Rut241DetailRow label="Firmware" value={device.firmware_version} />
          <Rut241DetailRow label="Asset" value={device.asset_serial ? `${device.asset_serial} (#${device.asset_id})` : `#${device.asset_id}`} />
          <Rut241DetailRow label="Customer" value={device.company_name} />

          <div style={{ marginTop: 28 }}><SectionLabel>Configuration</SectionLabel></div>
          <Rut241DetailRow label="Profile" value={device.configuration_profile} />
          <Rut241DetailRow label="Version" value={device.configuration_version} />

          <div style={{ marginTop: 28 }}><SectionLabel>eSIM</SectionLabel></div>
          {esim ? (
            <>
              <Rut241DetailRow label="Profile" value={esim.profileLabel} />
              <Rut241DetailRow label="ICCID" value={esim.iccidMasked || "Not shown"} />
              <Rut241DetailRow label="Status" value={esim.status} />
            </>
          ) : (
            <EmptyNote>No eSIM profile reserved yet.</EmptyNote>
          )}
        </div>

        <div style={{ flex: "1 1 300px" }}>
          <SectionLabel>Actions</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {has("reboot") && (
              <ActionButton onClick={() => callAction("/reboot")} disabled={actionBusy === "/reboot"} testId="rut241-action-reboot">
                {actionBusy === "/reboot" ? "Rebooting…" : "Reboot router"}
              </ActionButton>
            )}
            {has("diagnose_faults") && (
              <ActionButton onClick={() => setShowDiagnostics(true)} testId="rut241-action-diagnostics">Run SOLO AI Diagnostics</ActionButton>
            )}
            {has("reprovision") && !wanUsed && job && job.current_connection_method === "ESIM_BOOTSTRAP" && (
              <ActionButton onClick={() => callAction("/switch-to-wan")} disabled={actionBusy === "/switch-to-wan"} testId="rut241-action-switch-wan">
                {actionBusy === "/switch-to-wan" ? "Switching…" : "Switch to WAN (bootstrap failover)"}
              </ActionButton>
            )}
            {has("replace_esim") && (
              <ActionButton onClick={() => callAction("/replace-esim")} disabled={actionBusy === "/replace-esim"} testId="rut241-action-replace-esim">
                {actionBusy === "/replace-esim" ? "Replacing…" : "Replace eSIM"}
              </ActionButton>
            )}
            {has("reprovision") && !isReady && (
              <ActionButton onClick={() => callAction("/mark-ready")} disabled={actionBusy === "/mark-ready" || wanRemovalPending} testId="rut241-action-mark-ready">
                {actionBusy === "/mark-ready" ? "Checking…" : "Mark Ready (final health check)"}
              </ActionButton>
            )}
            {has("change_region") && (
              <ActionButton onClick={() => setShowRegionModal(true)} testId="rut241-action-change-region">Change region (full reprovision)</ActionButton>
            )}
            {has("view_logs") && (
              <ActionButton onClick={() => setShowLogs(true)} testId="rut241-action-logs">View logs</ActionButton>
            )}
            {has("archive_router") && (
              <ActionButton danger onClick={() => callAction("/archive")} disabled={actionBusy === "/archive"} testId="rut241-action-archive">
                {actionBusy === "/archive" ? "Archiving…" : "Archive router"}
              </ActionButton>
            )}
          </div>
        </div>
      </div>

      {showRegionModal && (
        <Rut241ChangeRegionModal
          currentRegion={device.deployment_region}
          busy={actionBusy === "/change-region"}
          onCancel={() => setShowRegionModal(false)}
          onSubmit={async (newRegion) => {
            const ok = await callAction("/change-region", "POST", { region: newRegion });
            if (ok) setShowRegionModal(false);
          }}
        />
      )}

      {showDiagnostics && <Rut241DiagnosticsModal routerId={routerId} onClose={() => setShowDiagnostics(false)} onSwitchToWan={() => callAction("/switch-to-wan")} />}
      {showLogs && <Rut241LogsModal events={events} onClose={() => setShowLogs(false)} />}
    </AdminShell>
  );
}

function Rut241DetailRow({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "7px 0", borderBottom: "1px solid rgba(0,0,0,0.06)" }}>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 11.5, letterSpacing: "0.04em", color: "rgba(0,0,0,0.5)" }}>{label}</span>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "#000", textAlign: "right" }}>{value || "—"}</span>
    </div>
  );
}

function Rut241ChangeRegionModal({ currentRegion, busy, onCancel, onSubmit }) {
  const [region, setRegion] = useState(currentRegion === "UK_EU" ? "US_NA" : "UK_EU");
  return (
    <ModalShell title="Change deployment region" onCancel={onCancel}>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(0,0,0,0.6)", marginBottom: 18, lineHeight: 1.6 }}>
        This is a full reprovisioning event — a new eSIM and configuration profile will be allocated, and a new provisioning job created. The existing job history is kept.
      </div>
      <MiniField label="New region">
        <select value={region} onChange={(e) => setRegion(e.target.value)} style={adminSelectStyle}>
          {Object.entries(RUT241_REGION_LABELS).filter(([v]) => v !== currentRegion).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
        </select>
      </MiniField>
      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <ActionButton onClick={onCancel}>Cancel</ActionButton>
        <ActionButton onClick={() => onSubmit(region)} disabled={busy}>{busy ? "Reprovisioning…" : "Confirm change"}</ActionButton>
      </div>
    </ModalShell>
  );
}

function Rut241DiagnosticsModal({ routerId, onClose, onSwitchToWan }) {
  const [state, setState] = useState({ status: "loading", data: null });

  useEffect(() => {
    fetch(`/api/admin/rut241/routers/${routerId}/diagnostics`, { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((data) => setState({ status: "ready", data }))
      .catch(() => setState({ status: "error", data: null }));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps -- mount-only

  return (
    <ModalShell title="SOLO AI Diagnostics" onCancel={onClose} wide>
      {state.status === "loading" && (
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(0,0,0,0.55)" }}>SOLO AI is reviewing this job's history…</div>
      )}
      {state.status === "error" && <ModalError>Couldn't load diagnostics.</ModalError>}
      {state.status === "ready" && (
        <div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(0,0,0,0.4)", marginBottom: 6 }}>
            Current stage
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "#000", marginBottom: 20 }}>{state.data.stage}</div>

          <div style={{ fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(0,0,0,0.4)", marginBottom: 6 }}>
            {state.data.likelyCause ? "Likely cause" : "Note"}
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "#000", marginBottom: 20, lineHeight: 1.6 }}>
            {state.data.likelyCause || state.data.recommendedAction}
          </div>

          {state.data.likelyCause && state.data.recommendedAction && (
            <>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(0,0,0,0.4)", marginBottom: 6 }}>
                Recommended action
              </div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "#000", marginBottom: 20, lineHeight: 1.6 }}>{state.data.recommendedAction}</div>
            </>
          )}

          {onSwitchToWan && (
            <ActionButton onClick={() => { onSwitchToWan(); onClose(); }} testId="rut241-diagnostics-switch-wan">Switch to WAN</ActionButton>
          )}
        </div>
      )}
    </ModalShell>
  );
}

function Rut241LogsModal({ events, onClose }) {
  return (
    <ModalShell title="Provisioning log" onCancel={onClose} wide>
      {events.length === 0 ? (
        <EmptyNote>No events logged yet.</EmptyNote>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10, maxHeight: 480, overflowY: "auto" }}>
          {events.map((e) => (
            <div key={e.id} style={{ borderBottom: "1px solid rgba(0,0,0,0.08)", paddingBottom: 10 }}>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "#000" }}>
                <strong>{e.stage}</strong> {e.message}
              </div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "rgba(0,0,0,0.45)", marginTop: 2 }}>{e.created_at}</div>
            </div>
          ))}
        </div>
      )}
    </ModalShell>
  );
}

Object.assign(window, { AdminRut241RouterDetailPage });
