/* Today — the shift-start screen. Commit model: INSTANT. Every control here
   applies on its own and raises an undo toast where the change is consequential;
   there is no Save on this screen.

   Four figures, then the ward board, then the work that is actually waiting on
   somebody. Every list runs its own predicate from metrics.js — none of them is
   a slice — and every figure names the array it counts. */
(() => {
  const { Button, Badge } = window.OriginDesignSystem_7c998b;

  function WardBoard({ data, onNavigate }) {
    const wards = wardRows(data.admissions, data.wardBeds);
    return (
      <div className="hd-ward">
        {wards.map((ward) => (
          <div className="hd-ward__cell" key={ward.ward}>
            <span className="hd-ward__top">
              <span className="hd-ward__name">{ward.label}</span>
              <span className="hd-ward__count">{ward.occupied}<span className="hd-footnote"> / {ward.beds}</span></span>
            </span>
            <BedGrid ward={ward} />
            <span className="hd-footnote">
              {ward.specialty} · {ward.free} free
              {ward.held ? " · " + ward.held + (ward.held === 1 ? " bed held" : " beds held") : ""}
              {ward.waiting ? " · " + ward.waiting + " waiting" : ""}
            </span>
          </div>
        ))}
      </div>
    );
  }

  function WaitingList({ rows, data, now, viewer, onNavigate, onAdmissionTransition }) {
    if (!rows.length) return <p className="hd-footnote">Nobody is waiting for a bed. Every request from the emergency department has a bed named against it.</p>;
    return (
      <div className="hd-rows">
        {rows.map((admission) => {
          const patient = patientById(data.patients, admission.patientId);
          const breached = ADMISSION_FLAGS.bedWaitBreached(admission, now);
          return (
            <div className="hd-row" key={admission.id}>
              <div className="hd-row__text">
                <span className="hd-row__title">
                  <PersonCell name={patient.name} avatar={patient.avatar} onOpen={() => onNavigate("/patients/" + patient.id)}
                    meta={wardName(admission.ward) + " · " + labelOf(ADMISSION_SOURCES, admission.source)} />
                </span>
                <span className="hd-row__note">{admission.reason} · requested {formatWhen(admission.requestedAt, now)}, <span className={breached ? "hd-warn" : ""}>{formatCountdown(admission.requestedAt, now)}</span></span>
              </div>
              <AllergyChips patient={patient} />
              <Transitions transitions={admissionTransitions(admission, viewer).filter((t) => t.primary)} onRun={(t) => onAdmissionTransition(admission, t)} />
            </div>
          );
        })}
      </div>
    );
  }

  function HeldList({ rows, data, now, viewer, onNavigate, onAdmissionTransition }) {
    if (!rows.length) return <p className="hd-footnote">No bed is being held. Everybody marked fit for discharge has gone home the same day.</p>;
    return (
      <div className="hd-rows">
        {rows.map((admission) => {
          const patient = patientById(data.patients, admission.patientId);
          const held = ADMISSION_FLAGS.dischargeHeld(admission, now);
          return (
            <div className="hd-row" key={admission.id}>
              <div className="hd-row__text">
                <span className="hd-row__title">
                  <PersonCell name={patient.name} avatar={patient.avatar} onOpen={() => onNavigate("/patients/" + patient.id)}
                    meta={wardName(admission.ward) + " " + admission.bed} />
                </span>
                <span className="hd-row__note">
                  Fit since {formatWhen(admission.fitAt, now)} · <span className={held ? "hd-warn" : ""}>{formatCountdown(admission.fitAt, now)}</span> · day {ADMISSION_FLAGS.lengthOfStayDays(admission, now)} of an expected {admission.expectedStayDays}
                </span>
              </div>
              <Transitions transitions={admissionTransitions(admission, viewer).filter((t) => t.primary)} onRun={(t) => onAdmissionTransition(admission, t)} />
            </div>
          );
        })}
      </div>
    );
  }

  /* The theatre list is a timed ladder rather than a table: the question it
     answers is "what happens next, and can it start". */
  function TheatreLadder({ rows, data, now, viewer, onNavigate, onInterventionTransition }) {
    if (!rows.length) return <p className="hd-footnote">Nothing is booked into a theatre today.</p>;
    return (
      <div className="hd-rows">
        {rows.map((intervention) => {
          const patient = patientById(data.patients, intervention.patientId);
          const noConsent = INTERVENTION_FLAGS.consentMissing(intervention);
          return (
            <div className="hd-row" key={intervention.id}>
              <span className="hd-row__time">{new Date(intervention.scheduledAt).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}</span>
              <div className="hd-row__text">
                <span className="hd-row__title">
                  <button type="button" className="hd-linkbtn" onClick={() => onNavigate("/interventions/" + intervention.id)}>{intervention.name}</button>
                </span>
                <span className="hd-row__note">
                  {patient.name} · {intervention.theatre ? labelOf(THEATRES, intervention.theatre) : "No theatre yet"} · {staffName(data.staff, intervention.surgeonId)} · {intervention.plannedMin} min planned
                </span>
              </div>
              <StatusBadge values={INTERVENTION_STATUS} value={intervention.status} />
              {noConsent ? <Badge size="sm" variant="warning">Consent not recorded</Badge> : null}
              <Transitions transitions={interventionTransitions(intervention, viewer).filter((t) => t.primary)} onRun={(t) => onInterventionTransition(intervention, t)} />
            </div>
          );
        })}
      </div>
    );
  }

  function TodayScreen({ data, now, viewer, onNavigate, onAdmissionTransition, onInterventionTransition, onReactToNote, onExport }) {
    const waiting = bedsWaiting(data.admissions);
    const breached = bedWaitsBreached(data.admissions, now);
    const occupied = onWard(data.admissions).concat(fitForDischarge(data.admissions));
    const held = fitForDischarge(data.admissions);
    const theatre = interventionsToday(data.interventions, now);
    const theatreWithoutConsent = theatre.filter((i) => INTERVENTION_FLAGS.consentMissing(i));
    const awaitingPharmacy = ordersAwaitingPharmacy(data.orders);
    const onCharts = awaitingPharmacy.concat(activeOrders(data.orders));
    const owed = mentionsOwed(data.comments, viewer.id);

    return (
      <>
        <PageHeader
          path="/"
          title="Today"
          sub={new Date(now).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" }) + " · " + HD_HOSPITAL.short + " · you are covering " + wardName(viewer.ward) + " ward"}
          actions={<ExportMenu scope={"Open admissions across all " + WARDS.length + " wards"} onExport={(format) => onExport("Ward board", "Open admissions across all " + WARDS.length + " wards", openAdmissions(data.admissions).length, format)} />}
        />
        <Figures items={[
          { label: "Waiting for a bed", value: waiting.length, qualifier: breached.length + " of them past four hours" },
          { label: "Beds occupied", value: occupied.length, qualifier: held.length + (held.length === 1 ? " held for somebody fit to go home" : " held for people fit to go home") },
          { label: "In theatre today", value: theatre.length, qualifier: theatreWithoutConsent.length + " without consent recorded" },
          { label: "Orders awaiting a pharmacist", value: awaitingPharmacy.length, qualifier: "of " + onCharts.length + " orders live on charts now" },
        ]} />

        <Band title="Ward board" note="Occupied beds per ward against the establishment in each ward's record. One pip per bed; amber where a bed is held for somebody fit to go home."
          actions={<Button variant="outline" size="sm" onClick={() => onNavigate("/wards")}>Wards and beds</Button>}>
          <WardBoard data={data} onNavigate={onNavigate} />
        </Band>

        <div className="hd-cols">
          <Band fill title={"Waiting for a bed (" + waiting.length + ")"} note="Every admission whose status is awaiting a bed, oldest request first.">
            <WaitingList rows={waiting.slice().sort((a, b) => a.requestedAt - b.requestedAt)} data={data} now={now} viewer={viewer} onNavigate={onNavigate} onAdmissionTransition={onAdmissionTransition} />
          </Band>
          <Band fill title={"Fit for discharge, still here (" + held.length + ")"} note="Marked fit by a consultant and not yet gone home.">
            <HeldList rows={held.slice().sort((a, b) => a.fitAt - b.fitAt)} data={data} now={now} viewer={viewer} onNavigate={onNavigate} onAdmissionTransition={onAdmissionTransition} />
          </Band>
        </div>

        <Band title={"Theatre list, today (" + theatre.length + ")"} note="Scheduled for today and not cancelled, in time order."
          actions={<Button variant="outline" size="sm" onClick={() => onNavigate("/interventions")}>All interventions</Button>}>
          <TheatreLadder rows={theatre} data={data} now={now} viewer={viewer} onNavigate={onNavigate} onInterventionTransition={onInterventionTransition} />
        </Band>

        <Band title={"Notes waiting on you (" + owed.length + ")"} note="Notes that mention you and that you have not written back on."
          actions={<Button variant="outline" size="sm" onClick={() => onNavigate("/feed")}>Open the feed</Button>}>
          {owed.length ? (
            <div className="hd-notes">
              {owed.map((comment) => (
                <div className="hd-noteitem" key={comment.id}>
                  <Note comment={comment} staff={data.staff} viewer={viewer} now={now} onReact={onReactToNote}
                    context={recordTitle(data, comment.record.type, comment.record.id)} />
                  <Button variant="outline" size="xs" onClick={() => onNavigate(recordRoute(data, comment.record))}>Open the record</Button>
                </div>
              ))}
            </div>
          ) : <p className="hd-footnote">Nothing mentions you without an answer. Every note that named you has had a reply from you since.</p>}
        </Band>
      </>
    );
  }

  Object.assign(window, { TodayScreen, TheatreLadder, WardBoard });
})();
