const adminInitialApprovals = [
  { id: "rebind", title: "Lost device re-bind", detail: "Ademola Oladipo requests device re-binding after identity check", tone: "gold", status: "pending" },
  { id: "import", title: "Lecturer import warnings", detail: "2 rows in Lecturers.xlsx need review before commit", tone: "blue", status: "pending" },
  { id: "manual", title: "No-smartphone exception", detail: "CSC 201 manual record submitted by Dr. Amina Bello", tone: "teal", status: "pending" }
];

const adminAlertFeed = [
  { id: "arts", title: "Faculty of Arts below target", detail: "Weekly attendance is 73% — lowest across the university", severity: "High", tone: "red" },
  { id: "importwarn", title: "Import validation warnings", detail: "Lecturers.xlsx · 2 rows missing department codes", severity: "Medium", tone: "gold" },
  { id: "geofence", title: "Venue geofence drift resolved", detail: "Science S2 radius auto-corrected to 60m", severity: "Low", tone: "green" },
  { id: "device", title: "Device re-bind pending", detail: "1 student re-binding awaits admin identity confirmation", severity: "Medium", tone: "blue" }
];

function AdminDashboardView({ dataset, checkedIn, onOpenWeb, setActiveTab }) {
  const liveSessions = dataset.sessions.filter((session) => session.live);
  return (
    <div className="mobile-panel-stack">
      <div className="mobile-stat-grid">
        <MobileStat label="Live sessions" value="24" tone="teal" />
        <MobileStat label="Risk alerts" value={checkedIn ? "17" : "18"} tone="gold" />
        <MobileStat label="Imports running" value="4" tone="blue" />
        <MobileStat label="Verified devices" value="5,980" tone="green" />
      </div>

      <div className="mobile-list-head-row">
        <h3 className="mobile-section-heading">Live sessions now</h3>
        <button className="mini-action" onClick={() => setActiveTab("Monitor")} type="button">View all</button>
      </div>
      <div className="mobile-list">
        {liveSessions.map((session) => (
          <div className="mobile-list-row" key={session.course}>
            <div>
              <strong>{session.course} · {session.title}</strong>
              <span>{session.venue} · {session.lecturer}</span>
              <div className="row-bar"><div style={{ width: `${session.progress}%` }}></div></div>
            </div>
            <Badge tone="green">Live</Badge>
          </div>
        ))}
      </div>

      <GhostButton onClick={onOpenWeb}>Open web portal</GhostButton>
    </div>
  );
}

function AdminApprovalsView({ approvals, onDecide }) {
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Approvals queue</h2>
      {approvals.map((approval) => (
        <div className="approval-card" key={approval.id}>
          <div className="approval-top">
            <div>
              <strong>{approval.title}</strong>
              <span>{approval.detail}</span>
            </div>
            {approval.status === "pending" ? (
              <Badge tone={approval.tone}>Pending</Badge>
            ) : approval.status === "approved" ? (
              <Badge tone="green">Approved</Badge>
            ) : (
              <Badge tone="red">Rejected</Badge>
            )}
          </div>
          {approval.status === "pending" ? (
            <div className="approval-actions">
              <Button onClick={() => onDecide(approval.id, "approved")} tone="success">Approve</Button>
              <GhostButton className="danger" onClick={() => onDecide(approval.id, "rejected")}>Reject</GhostButton>
            </div>
          ) : (
            <small className="approval-decided">Decision recorded on mobile · synced to audit trail</small>
          )}
        </div>
      ))}
      <div className="mobile-note">Bulk imports, rule changes, and user management remain web-portal actions.</div>
    </div>
  );
}

function AdminMonitorView({ dataset }) {
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Live monitoring</h2>
      <div className="mobile-list">
        {dataset.sessions.map((session) => (
          <div className="mobile-list-row" key={session.course}>
            <div>
              <strong>{session.course} · {session.title}</strong>
              <span>{session.present} present · {session.absent} absent · {session.venue}</span>
              <div className="row-bar"><div className={session.progress >= 85 ? "" : "risk"} style={{ width: `${session.progress}%` }}></div></div>
            </div>
            {session.live ? <Badge tone="green">Live</Badge> : <Badge tone="blue">{session.progress}%</Badge>}
          </div>
        ))}
      </div>
      <MobileList items={[
        { title: "Geofence health", detail: "86 venues reporting within configured radius", state: "Healthy", tone: "green" },
        { title: "Device signing", detail: "No signature failures in the last 24 hours", state: "Normal", tone: "teal" }
      ]} />
    </div>
  );
}

function AdminAlertsView({ acknowledged, onAcknowledge }) {
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Risk alerts</h2>
      <div className="mobile-list">
        {adminAlertFeed.map((alertItem) => {
          const acked = Boolean(acknowledged[alertItem.id]);
          return (
            <div className="mobile-list-row" key={alertItem.id}>
              <div>
                <strong>{alertItem.title}</strong>
                <span>{alertItem.detail}</span>
              </div>
              <div className="roster-meta">
                <Badge tone={acked ? "teal" : alertItem.tone}>{acked ? "Acknowledged" : alertItem.severity}</Badge>
                {!acked && (
                  <button className="mini-action" onClick={() => onAcknowledge(alertItem.id)} type="button">Acknowledge</button>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <div className="mobile-note">Alerts originate from Core risk rules — acknowledgement is logged for leadership review.</div>
    </div>
  );
}

function AdminMobileView({ dataset, checkedIn, activeTab, setActiveTab }) {
  const [approvals, setApprovals] = React.useState(adminInitialApprovals);
  const [acknowledged, setAcknowledged] = React.useState({ geofence: true });
  const [toastElement, showToast] = useLocalToast();

  function decide(id, status) {
    setApprovals((current) => current.map((item) => (item.id === id ? { ...item, status } : item)));
    const item = approvals.find((entry) => entry.id === id);
    showToast(status === "approved" ? `Approved: ${item.title}` : `Rejected: ${item.title}`);
  }

  let view = null;
  if (activeTab === "Approvals") {
    view = <AdminApprovalsView approvals={approvals} onDecide={decide} />;
  } else if (activeTab === "Monitor") {
    view = <AdminMonitorView dataset={dataset} />;
  } else if (activeTab === "Alerts") {
    view = (
      <AdminAlertsView
        acknowledged={acknowledged}
        onAcknowledge={(id) => setAcknowledged((current) => ({ ...current, [id]: true }))}
      />
    );
  } else {
    view = (
      <AdminDashboardView
        dataset={dataset}
        checkedIn={checkedIn}
        onOpenWeb={() => showToast("Web portal opens in browser (demo)")}
        setActiveTab={setActiveTab}
      />
    );
  }

  return (
    <>
      <WebPortalBanner />
      {view}
      {toastElement}
    </>
  );
}

Object.assign(window, {
  AdminMobileView
});
