const lecturerManualReasons = ["No smartphone", "Device issue", "App failure"];

function buildLecturerRoster(students, checkedIn, manualRecords) {
  const roster = students.map((student) => {
    const isDemoStudent = student.id === "ademola";
    const state = isDemoStudent && checkedIn ? "Present" : student.base;
    return {
      id: student.id,
      name: student.name,
      matric: student.matric,
      device: student.device,
      state,
      time: state === "Present" ? (isDemoStudent ? "10:02 AM" : "10:01 AM") : null
    };
  });
  return roster.concat(manualRecords);
}

function LecturerSessionView({ dataset, manualCount, onOpenRoster, onRunCheckIn }) {
  const presentCount = 78 + (dataset.studentCheckedIn ? 1 : 0) + manualCount;
  const absentCount = 90 - presentCount;
  const progressPct = Math.round((presentCount / 90) * 100);
  const checkedIn = dataset.studentCheckedIn;

  return (
    <div className="mobile-panel-stack">
      <div className="mobile-card-highlight">
        <div className="live-chip-row">
          <Badge tone="green">SESSION OPEN</Badge>
          <span className="live-time">Started 10:00</span>
        </div>
        <h2>{dataset.courseCode} · Data Structures</h2>
        <p>{dataset.venue} · ends 11:30 · token expires 10:12</p>
      </div>

      <div className="mobile-token-card">
        <span>Session token</span>
        <strong>CSC201 · A102 · NONCE-7K2</strong>
      </div>

      <div className="mobile-stat-grid">
        <MobileStat label="Present" value={String(presentCount)} tone="green" />
        <MobileStat label="Absent" value={String(absentCount)} tone="red" />
        <MobileStat label="Manual" value={String(manualCount)} tone="gold" />
        <MobileStat label="Progress" value={`${progressPct}%`} tone="teal" />
      </div>

      <Button disabled={checkedIn} onClick={onRunCheckIn} tone="success">{checkedIn ? "Ademola synced ✓" : "Simulate live check-in"}</Button>
      <GhostButton onClick={onOpenRoster}>Open live roster</GhostButton>
    </div>
  );
}

function LecturerRosterView({ dataset, checkedIn, filter, manualRecords, onFilter, onOpenManual, onRunCheckIn, query, onQuery }) {
  const roster = buildLecturerRoster(dataset.students, checkedIn, manualRecords);
  const filtered = roster.filter((row) => {
    const matchesQuery = `${row.name} ${row.matric}`.toLowerCase().includes(query.trim().toLowerCase());
    const matchesFilter =
      filter === "All" ||
      (filter === "Manual" ? row.manual : row.state === filter);
    return matchesQuery && matchesFilter;
  });

  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Live roster · {roster.length} shown of 90</h2>

      <div className="search-field">
        <Icon name="search" size={14} />
        <input onChange={(event) => onQuery(event.target.value)} placeholder="Search name or matric no." value={query} />
      </div>

      <div className="chip-row">
        {["All", "Present", "Waiting", "Absent", "Manual"].map((chip) => (
          <button className={`chip ${filter === chip ? "active" : ""}`} key={chip} onClick={() => onFilter(chip)} type="button">{chip}</button>
        ))}
      </div>

      {filtered.length === 0 && <div className="mobile-note">No students match this search or filter.</div>}

      <div className="mobile-list">
        {filtered.map((row) => {
          const tone = row.manual ? "gold" : row.state === "Present" ? "green" : row.state === "Absent" ? "red" : "blue";
          return (
            <div className="mobile-list-row" key={`${row.id}-${row.matric}`}>
              <div>
                <strong>{row.name}</strong>
                <span>{row.matric} · {row.device}{row.reason ? ` · ${row.reason}` : ""}</span>
              </div>
              <div className="roster-meta">
                <Badge tone={tone}>{row.manual ? `Manual` : row.state}</Badge>
                {row.time && <small>{row.time}</small>}
              </div>
            </div>
          );
        })}
      </div>

      <div className="mobile-action-grid">
        <Button onClick={onOpenManual}>Manual · no smartphone</Button>
        <GhostButton disabled={checkedIn} onClick={onRunCheckIn}>{checkedIn ? "Synced" : "Refresh roster"}</GhostButton>
      </div>
    </div>
  );
}

function LecturerManualForm({ dataset, checkedIn, onBack, onSaveRecord }) {
  const eligible = buildLecturerRoster(dataset.students, checkedIn, []).filter((row) => row.state !== "Present");
  const [studentId, setStudentId] = React.useState(eligible[0]?.id || "");
  const [reason, setReason] = React.useState(lecturerManualReasons[0]);

  function save() {
    const student = eligible.find((row) => row.id === studentId);
    if (!student) return;
    onSaveRecord({
      id: `manual-${Date.now()}`,
      name: student.name,
      matric: student.matric,
      device: "Manual entry",
      state: "Present",
      manual: true,
      reason,
      time: null
    });
  }

  return (
    <div className="mobile-panel-stack">
      <SubViewHead onBack={onBack} title="Manual attendance" />

      <div className="mobile-note">
        For students without a working smartphone. The record is flagged <strong>Manual</strong> and included in the class audit trail.
      </div>

      <label className="field-label">
        <span>Student</span>
        <select className="field-select" onChange={(event) => setStudentId(event.target.value)} value={studentId}>
          {eligible.map((row) => (
            <option key={row.id} value={row.id}>{row.name} · {row.matric} ({row.state})</option>
          ))}
        </select>
      </label>

      <div className="field-label">
        <span>Reason</span>
        <div className="chip-row wrap">
          {lecturerManualReasons.map((item) => (
            <button className={`chip ${reason === item ? "active" : ""}`} key={item} onClick={() => setReason(item)} type="button">{item}</button>
          ))}
        </div>
      </div>

      <label className="field-label">
        <span>Note (optional)</span>
        <textarea className="field-textarea" placeholder="e.g. Device screen cracked this morning" rows="3"></textarea>
      </label>

      <div className="mobile-action-grid">
        <Button onClick={save} tone="success">Save manual record</Button>
        <GhostButton onClick={onBack}>Cancel</GhostButton>
      </div>
    </div>
  );
}

function LecturerAlertsView({ dataset, acknowledged, manualRecords, onAcknowledge }) {
  const alerts = [
    { id: "fatima", title: "Fatima Usman", detail: "Absent and below the eligibility threshold (63%)", tone: "red", state: "High risk" },
    ...(manualRecords.length ? [{
      id: "manual",
      title: "Manual record added",
      detail: `${manualRecords.length} no-smartphone entry needs audit review`,
      tone: "gold",
      state: "Review"
    }] : []),
    { id: "summary", title: "Class summary", detail: "CSC 201 live attendance is tracking above last week", tone: "green", state: "Live" }
  ];

  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Alerts</h2>
      <div className="mobile-list">
        {alerts.map((alert) => {
          const acked = Boolean(acknowledged[alert.id]);
          return (
            <div className="mobile-list-row" key={alert.id}>
              <div>
                <strong>{alert.title}</strong>
                <span>{alert.detail}</span>
              </div>
              <div className="roster-meta">
                <Badge tone={acked ? "teal" : alert.tone}>{acked ? "Acknowledged" : alert.state}</Badge>
                {!acked && alert.tone !== "green" && (
                  <button className="mini-action" onClick={() => onAcknowledge(alert.id)} type="button">Acknowledge</button>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <MiniChart values={[55, 68, 73, 81, dataset.studentCheckedIn ? 88 : 84, 79]} />
      <div className="mobile-note">Risk alerts sync to the HOD dashboard and student app in real time.</div>
    </div>
  );
}

function LecturerReportView({ dataset, manualCount, showToast }) {
  const presentCount = 78 + (dataset.studentCheckedIn ? 1 : 0) + manualCount;
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Class report</h2>
      <div className="mobile-card-highlight compact">
        <Badge tone="teal">CSC 201 · Today 10:00 – 11:30</Badge>
        <h2>{presentCount}/90 present</h2>
        <p>{90 - presentCount} absent · {manualCount} manual · venue geofence enforced</p>
      </div>
      <MiniChart values={[64, 71, 69, 78, 82, dataset.studentCheckedIn ? 88 : 84]} />
      <MobileList items={[
        { title: "Attendance rate", detail: "Verified check-ins vs enrolled students", state: `${Math.round((presentCount / 90) * 100)}%`, tone: "green" },
        { title: "Eligibility impact", detail: "1 student crossed below threshold today", state: "Updated", tone: "gold" },
        { title: "Audit trail", detail: "Token, device key, GPS, nonce recorded in Core", state: "Complete", tone: "blue" }
      ]} />
      <Button onClick={() => showToast("Report exported (demo)")}>Export CSV report</Button>
      <div className="mobile-note">Full session management and historical reports are available on the lecturer web portal.</div>
    </div>
  );
}

function LecturerMobileView({ dataset, checkedIn, activeTab, setActiveTab, onRunCheckIn }) {
  const [manualRecords, setManualRecords] = React.useState([]);
  const [mode, setMode] = React.useState(null);
  const [query, setQuery] = React.useState("");
  const [filter, setFilter] = React.useState("All");
  const [acknowledged, setAcknowledged] = React.useState({});
  const [toastElement, showToast] = useLocalToast();

  function saveManualRecord(record) {
    setManualRecords((current) => current.concat(record));
    setMode(null);
    setFilter("All");
    showToast(`${record.name} marked present (manual)`);
  }

  let view = null;
  if (mode === "manual") {
    view = (
      <LecturerManualForm
        checkedIn={checkedIn}
        dataset={dataset}
        onBack={() => setMode(null)}
        onSaveRecord={saveManualRecord}
      />
    );
  } else if (activeTab === "Roster") {
    view = (
      <LecturerRosterView
        checkedIn={checkedIn}
        dataset={dataset}
        filter={filter}
        manualRecords={manualRecords}
        onFilter={setFilter}
        onOpenManual={() => setMode("manual")}
        onQuery={setQuery}
        onRunCheckIn={onRunCheckIn}
        query={query}
      />
    );
  } else if (activeTab === "Alerts") {
    view = (
      <LecturerAlertsView
        acknowledged={acknowledged}
        dataset={{ ...dataset, studentCheckedIn: checkedIn }}
        manualRecords={manualRecords}
        onAcknowledge={(id) => setAcknowledged((current) => ({ ...current, [id]: true }))}
      />
    );
  } else if (activeTab === "Report") {
    view = <LecturerReportView dataset={{ ...dataset, studentCheckedIn: checkedIn }} manualCount={manualRecords.length} showToast={showToast} />;
  } else {
    view = (
      <LecturerSessionView
        dataset={{ ...dataset, studentCheckedIn: checkedIn }}
        manualCount={manualRecords.length}
        onOpenRoster={() => setActiveTab("Roster")}
        onRunCheckIn={onRunCheckIn}
      />
    );
  }

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

Object.assign(window, {
  LecturerMobileView
});
