// System Management — per-unit hardware dashboard for a single physical
// asset. Reached by clicking a row in either the reseller portal's "My
// assets" table (reseller-portal-dashboard.jsx) or the admin Assets page
// (admin-assets-page.jsx); which one determines `viewerType` ("reseller"
// | "admin"), threaded through onNavigate's opts (see app.jsx) as
// { unitId, viewerType }.
//
// Reseller and admin share the exact same 12-tab shell and General-tab
// layout — only the data source (routes/portal.ts vs
// routes/admin-assets.ts), the outer chrome (ResellerShell vs AdminShell)
// and one extra admin-only control (grant/revoke this unit's reseller-
// side access) differ. Every other tab beyond General is a placeholder
// today ("we will add all these later" — product decision); the real
// EFOY / solar-charger / router / ARC / NVR integrations will populate
// unit_telemetry (see migrations/0010_unit_management.sql and
// src/lib/telemetry.ts) once they exist — until then every unit gets
// realistic demo data, lazily generated on first view.
//
// Uses unique `UM_`-prefixed local helper names throughout, deliberately
// NOT reusing the generic inputStyle/SectionLabel/MiniField/etc. names
// that several other top-level site/*.jsx files declare — this codebase
// loads every file as a global <script type="text/babel"> tag with no
// module isolation, and an unresolved naming-collision issue (see
// support-page.jsx investigation notes) makes shared generic names risky
// until that's understood. Prefixing costs nothing and avoids the risk.

const UM_TABS = [
  { id: "general", label: "General" },
  { id: "cameras", label: "Cameras" },
  { id: "settings", label: "Settings" },
  { id: "efoy", label: "EFOY" },
  { id: "speakers", label: "Speakers" },
  { id: "alarm", label: "Alarm" },
  { id: "events", label: "Events" },
  { id: "errors", label: "Errors" },
  { id: "schedules", label: "Schedules" },
  { id: "arc", label: "ARC Integration" },
  { id: "notifications", label: "Notifications" },
  { id: "system", label: "System" },
];

function UnitManagementPage({ onNavigate, unitId, viewerType }) {
  const isAdmin = viewerType === "admin";
  const [state, setState] = useState({ status: "loading", viewer: null, unit: null, telemetry: null, error: "" });
  const [activeSubTab, setActiveSubTab] = useState("general");
  const [toggleBusy, setToggleBusy] = useState(null);
  const [accessBusy, setAccessBusy] = useState(false);

  const telemetryUrl = isAdmin
    ? `/api/admin/units/${unitId}/telemetry`
    : `/api/portal/assets/${unitId}/telemetry`;
  const toggleUrl = isAdmin
    ? `/api/admin/units/${unitId}/toggle`
    : `/api/portal/assets/${unitId}/toggle`;

  const load = () => {
    if (!unitId) { setState({ status: "error", viewer: null, unit: null, telemetry: null, error: "No unit selected." }); return; }
    const meUrl = isAdmin ? "/api/admin/me" : "/api/portal/me";
    Promise.all([
      fetch(meUrl, { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject({ authFailed: true }))),
      fetch(telemetryUrl, { credentials: "same-origin" }).then(async (r) => {
        const data = await r.json().catch(() => ({}));
        if (!r.ok) throw { authFailed: false, message: data.error || "Couldn't load this unit." };
        return data;
      }),
    ])
      .then(([me, unitData]) => {
        setState({
          status: "ready",
          viewer: isAdmin ? me.admin : { user: me.user, company: me.company },
          unit: unitData.unit, telemetry: unitData.telemetry, error: "",
        });
      })
      .catch((err) => {
        if (err && err.authFailed) { onNavigate(isAdmin ? "admin-login" : "reseller-login"); return; }
        setState({ status: "error", viewer: null, unit: null, telemetry: null, error: (err && err.message) || "Couldn't load this unit." });
      });
  };

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

  const handleToggle = async (key, next) => {
    setToggleBusy(key);
    try {
      const res = await fetch(toggleUrl, {
        method: "PATCH", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ key, on: next }),
      });
      if (res.ok) {
        setState((s) => ({ ...s, telemetry: { ...s.telemetry, [`${key}_on`]: next ? 1 : 0 } }));
      }
    } finally { setToggleBusy(null); }
  };

  const handleToggleAccess = async () => {
    if (!isAdmin) return;
    setAccessBusy(true);
    try {
      const res = await fetch(`/api/admin/units/${unitId}/management-access`, {
        method: "PATCH", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ enabled: !state.unit.management_access_enabled }),
      });
      if (res.ok) {
        setState((s) => ({ ...s, unit: { ...s.unit, management_access_enabled: s.unit.management_access_enabled ? 0 : 1 } }));
      }
    } finally { setAccessBusy(false); }
  };

  const backAction = (
    <button
      type="button"
      onClick={() => onNavigate(isAdmin ? "admin-assets" : "portal-dashboard")}
      data-testid="unit-management-back"
      style={{
        background: "none", border: "1px solid rgba(0,0,0,0.25)",
        color: "rgba(0,0,0,0.75)", cursor: "pointer", padding: "10px 18px",
        fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 500,
        letterSpacing: "0.14em", textTransform: "uppercase",
      }}
    >
      &larr; Back to assets
    </button>
  );

  let body;
  if (state.status === "loading") {
    body = <UM_EmptyNote>Loading unit&hellip;</UM_EmptyNote>;
  } else if (state.status === "error") {
    body = <UM_EmptyNote>{state.error}</UM_EmptyNote>;
  } else {
    body = (
      <UM_Dashboard
        unit={state.unit}
        telemetry={state.telemetry}
        activeSubTab={activeSubTab}
        setActiveSubTab={setActiveSubTab}
        onToggle={handleToggle}
        toggleBusy={toggleBusy}
        isAdmin={isAdmin}
        accessBusy={accessBusy}
        onToggleAccess={handleToggleAccess}
      />
    );
  }

  if (isAdmin) {
    return (
      <AdminShell
        admin={state.viewer} page="admin-assets" onNavigate={onNavigate}
        subtitle="Staff only" title={state.unit ? `${state.unit.serial_number} · System Management` : "System Management"}
        actions={backAction}
      >
        {body}
      </AdminShell>
    );
  }

  return (
    <ResellerShell
      page="portal-dashboard" onNavigate={onNavigate}
      userName={state.viewer && state.viewer.user ? state.viewer.user.name : undefined}
      companyName={state.viewer && state.viewer.company ? state.viewer.company.name : undefined}
      subtitle="System Management"
      title={state.unit ? `${state.unit.serial_number}` : "System Management"}
      actions={backAction}
    >
      {body}
    </ResellerShell>
  );
}

function UM_Dashboard({ unit, telemetry, activeSubTab, setActiveSubTab, onToggle, toggleBusy, isAdmin, accessBusy, onToggleAccess }) {
  const accessEnabled = !!unit.management_access_enabled;
  return (
    <div>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "flex-end",
        flexWrap: "wrap", gap: 14, marginBottom: 22,
      }}>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "rgba(0,0,0,0.55)" }}>
          {unit.product_name}
          {unit.current_company_name && <> &middot; {unit.current_company_name}</>}
        </div>
        {isAdmin && (
          <button
            type="button" onClick={onToggleAccess} disabled={accessBusy}
            data-testid="unit-management-toggle-access"
            style={{
              background: accessEnabled ? "transparent" : "#000",
              color: accessEnabled ? "rgba(190,40,40,0.9)" : "#fff",
              border: `1px solid ${accessEnabled ? "rgba(190,40,40,0.5)" : "#000"}`,
              padding: "10px 18px", cursor: accessBusy ? "not-allowed" : "pointer",
              opacity: accessBusy ? 0.6 : 1,
              fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 500,
              letterSpacing: "0.14em", textTransform: "uppercase",
            }}
          >
            {accessEnabled ? "Revoke reseller access" : "Allow reseller access"}
          </button>
        )}
      </div>

      {!accessEnabled && (
        <div style={{
          background: "rgba(190,40,40,0.08)", border: "1px solid rgba(190,40,40,0.35)",
          color: "rgba(140,30,30,0.95)", padding: "12px 16px", marginBottom: 22,
          fontFamily: "var(--font-body)", fontSize: 13, letterSpacing: "0.01em",
        }}>
          {isAdmin
            ? "This unit's System Management access is currently revoked for the reseller — they cannot view this dashboard until it's re-enabled."
            : "System Management access for this unit has been disabled by Solo staff."}
        </div>
      )}

      {/* 12-tab sub-navigation */}
      <div style={{ borderBottom: "1px solid rgba(0,0,0,0.12)", marginBottom: 28, overflowX: "auto" }}>
        <div style={{ display: "flex", gap: 4, minWidth: "max-content" }}>
          {UM_TABS.map((tab) => {
            const active = activeSubTab === tab.id;
            return (
              <button
                key={tab.id} type="button" onClick={() => setActiveSubTab(tab.id)}
                data-testid={`unit-tab-${tab.id}`}
                style={{
                  background: "none", border: "none", cursor: "pointer",
                  padding: "14px 4px", marginRight: 24, marginBottom: -1, whiteSpace: "nowrap",
                  borderBottom: `2px solid ${active ? "rgba(180,110,0,0.85)" : "transparent"}`,
                  color: active ? "#000" : "rgba(0,0,0,0.55)",
                  fontFamily: "var(--font-body)", fontSize: 12,
                  fontWeight: active ? 600 : 500, letterSpacing: "0.06em",
                  textTransform: "uppercase",
                }}
              >
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {activeSubTab === "general" ? (
        <UM_GeneralTab unit={unit} telemetry={telemetry} onToggle={onToggle} toggleBusy={toggleBusy} />
      ) : (
        <UM_ComingSoon tab={UM_TABS.find((t) => t.id === activeSubTab)} />
      )}
    </div>
  );
}

function UM_ComingSoon({ tab }) {
  return (
    <div data-testid="unit-tab-panel-coming-soon" style={{
      background: "rgba(0,0,0,0.02)", border: "1px solid rgba(0,0,0,0.1)",
      padding: "40px 32px", textAlign: "center",
    }}>
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 9, letterSpacing: "0.2em",
        textTransform: "uppercase", color: "rgba(0,0,0,0.4)", marginBottom: 12, fontWeight: 500,
      }}>Coming soon</div>
      <div style={{
        fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18,
        textTransform: "uppercase", color: "rgba(0,0,0,0.8)", marginBottom: 8,
      }}>{tab ? tab.label : ""}</div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "rgba(0,0,0,0.5)" }}>
        This integration hasn't been connected yet — it'll appear here once it's live.
      </div>
    </div>
  );
}

// ─────────────────────────── General tab ───────────────────────────
// A light "device dashboard" panel, pixel-matched to the reference
// mock-up, embedded inside the dark portal/admin chrome. Cards are
// hidden per-product hardware profile (has_efoy / has_pv_charger / etc,
// from products table) rather than being tower-hardware-exclusive — see
// migrations/0010_unit_management.sql.

function UM_GeneralTab({ unit, telemetry, onToggle, toggleBusy }) {
  const fmt = (n, dp) => (n === null || n === undefined ? "\u2014" : Number(n).toFixed(dp));

  return (
    <div style={{
      background: "#F6F2E9", border: "1px solid #E2DCCB",
      padding: "32px", display: "grid",
      gridTemplateColumns: "280px 1fr 280px", gap: 28,
    }}>
      {/* Left column */}
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        {!!unit.has_efoy && (
          <UM_Card title="EFOY" badge={{ label: "Standby", tone: "grey" }}>
            <UM_BigValue>{fmt(telemetry.efoy_power_w, 2)} W</UM_BigValue>
            <UM_Row label="Current" value={`${fmt(telemetry.efoy_current_a, 2)} A`} />
            <UM_Row label="Voltage" value={`${fmt(telemetry.efoy_voltage_v, 2)} V`} />
            <UM_Row label="Run Time" value={UM_formatRuntime(telemetry.efoy_runtime_minutes)} />
            <UM_Row label="Fuel Level" value={`${fmt(telemetry.efoy_fuel_percent, 0)}% (${fmt(telemetry.efoy_fuel_litres, 3)}l)`} />
          </UM_Card>
        )}

        {!!unit.has_mains_power && (
          <UM_Card title="Mains Power">
            <UM_BigValue small>{telemetry.mains_connected ? "Connected" : "Disconnected"}</UM_BigValue>
          </UM_Card>
        )}

        {!!unit.has_pv_charger && (
          <UM_Card title="PV Charger" badge={{ label: telemetry.pv_status === "generating" ? "GENERATING" : "Standby", tone: telemetry.pv_status === "generating" ? "blue" : "grey" }}>
            <UM_BigValue>{fmt(telemetry.pv_power_w, 0)} W</UM_BigValue>
            <UM_Row label="Panel Voltage" value={`${fmt(telemetry.pv_panel_voltage_v, 2)} V`} />
            <UM_Row label="Output Current" value={`${fmt(telemetry.pv_output_current_a, 2)} A`} />
            <UM_Row label="Run Time" value={UM_formatRuntime(telemetry.pv_runtime_minutes)} />
            <UM_Row label="Fuel Level" value={`${fmt(telemetry.pv_fuel_percent, 0)}% (${fmt(telemetry.pv_fuel_litres, 3)}l)`} />
          </UM_Card>
        )}
      </div>

      {/* Center — product image */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <TowerSchematic width={220} height={340} stroke="#3A3630" />
        <div style={{
          fontFamily: "var(--font-body)", fontSize: 13, color: "#7A7466",
          marginTop: 14, textAlign: "center",
        }}>{unit.product_name}</div>
        <div style={{
          fontFamily: "monospace", fontSize: 12, color: "#3A3630",
          marginTop: 4, textAlign: "center",
        }}>{unit.serial_number}</div>
      </div>

      {/* Right column */}
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <UM_Card title="Controls">
          {!!unit.has_strobe && (
            <UM_ToggleRow label="Strobe" on={!!telemetry.strobe_on} busy={toggleBusy === "strobe"} onChange={(v) => onToggle("strobe", v)} />
          )}
          {!!unit.has_alarm && (
            <UM_ToggleRow label="Armed" on={!!telemetry.armed_on} busy={toggleBusy === "armed"} onChange={(v) => onToggle("armed", v)} />
          )}
          {!!unit.has_cameras && (
            <UM_ToggleRow label="Cameras" on={!!telemetry.cameras_on} busy={toggleBusy === "cameras"} onChange={(v) => onToggle("cameras", v)} last />
          )}
        </UM_Card>

        <UM_Card title="Power">
          <UM_Row label="Power" value={`${fmt(telemetry.power_w, 2)} W`} />
          <UM_Row label="Current" value={`${fmt(telemetry.power_current_a, 4)} A`} last />
        </UM_Card>

        {!!unit.has_router && (
          <UM_Card title="Internet Router">
            <UM_Row label="Operator" value={telemetry.router_operator || "\u2014"} />
            <UM_Row label="Signal" value={telemetry.router_signal_percent != null ? `${fmt(telemetry.router_signal_percent, 0)}% (${fmt(telemetry.router_signal_dbm, 0)}dBm)` : "\u2014"} />
            <UM_Row label="WWAN IP" value={telemetry.router_wwan_ip || "\u2014"} />
            <UM_Row label="Active SIM" value={telemetry.router_active_sim || "\u2014"} />
            <UM_Row label="Firmware" value={telemetry.router_firmware || "\u2014"} />
            <UM_Row label="Temperature" value={telemetry.router_temperature_c != null ? `${fmt(telemetry.router_temperature_c, 0)} \u00b0C` : "\u2014"} />
            <UM_Row label="CPU Load" value={telemetry.router_cpu_load != null ? fmt(telemetry.router_cpu_load, 2) : "\u2014"} />
            <UM_Row label="MAC" value={telemetry.router_mac || "\u2014"} last />
          </UM_Card>
        )}
      </div>
    </div>
  );
}

function UM_formatRuntime(minutes) {
  if (minutes === null || minutes === undefined) return "\u2014";
  const h = Math.floor(minutes / 60);
  const m = Math.round(minutes % 60);
  return `${h}h ${m}min`;
}

function UM_Card({ title, badge, children }) {
  return (
    <div style={{ background: "#FFFFFF", border: "1px solid #E2DCCB", padding: "18px 18px 14px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <div style={{
          fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 700,
          letterSpacing: "0.04em", textTransform: "uppercase", color: "#3A3630",
        }}>{title}</div>
        {badge && <UM_Badge label={badge.label} tone={badge.tone} />}
      </div>
      {children}
    </div>
  );
}

function UM_Badge({ label, tone }) {
  const tones = {
    grey: { bg: "#EDEAE1", fg: "#8A8474" },
    blue: { bg: "#DCEEFB", fg: "#2C7BB0" },
    green: { bg: "#DFF3E3", fg: "#2C8C4C" },
  };
  const c = tones[tone] || tones.grey;
  return (
    <span style={{
      background: c.bg, color: c.fg, fontFamily: "var(--font-body)",
      fontSize: 10, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase",
      padding: "4px 10px", borderRadius: 3,
    }}>{label}</span>
  );
}

function UM_BigValue({ children, small }) {
  return (
    <div style={{
      fontFamily: "var(--font-display)", fontWeight: 700,
      fontSize: small ? 18 : 26, color: "#1A1712", marginBottom: 10,
    }}>{children}</div>
  );
}

function UM_Row({ label, value, last }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", gap: 12,
      padding: "6px 0", borderBottom: last ? "none" : "1px solid #EEE9DD",
      fontFamily: "var(--font-body)", fontSize: 12.5,
    }}>
      <span style={{ color: "#8A8474" }}>{label}</span>
      <span style={{ color: "#1A1712", fontWeight: 500 }}>{value}</span>
    </div>
  );
}

function UM_ToggleRow({ label, on, busy, onChange, last }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12,
      padding: "8px 0", borderBottom: last ? "none" : "1px solid #EEE9DD",
    }}>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "#1A1712" }}>{label}</span>
      <button
        type="button" disabled={busy} onClick={() => onChange(!on)}
        data-testid={`unit-toggle-${label.toLowerCase()}`}
        style={{
          width: 42, height: 24, borderRadius: 12, border: "none", padding: 2,
          background: on ? "#3FAE5C" : "#D5D0C3", cursor: busy ? "not-allowed" : "pointer",
          opacity: busy ? 0.6 : 1, display: "flex", justifyContent: on ? "flex-end" : "flex-start",
          transition: "background 140ms",
        }}
      >
        <span style={{ width: 20, height: 20, borderRadius: "50%", background: "#fff", display: "block" }} />
      </button>
    </div>
  );
}

function UM_EmptyNote({ children }) {
  return (
    <div style={{
      fontFamily: "var(--font-body)", fontSize: 14,
      color: "rgba(0,0,0,0.5)", padding: "40px 0",
    }}>{children}</div>
  );
}

Object.assign(window, { UnitManagementPage });
