/* Reports — the six figures the hospital is actually judged on, each one a rate
   with its own denominator named, and each one drilling through to the rows it
   was computed from. Commit model: INSTANT (there is nothing to commit; the only
   controls are the export and the links).

   Every figure here is `reportFigures(data, now)` in metrics.js — the same
   arrays the destination screens render, so no number on this screen exists
   only here. */
(() => {
  const {
    Button, Badge, Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
  } = window.OriginDesignSystem_7c998b;

  function Rate({ label, value, detail, route, onNavigate, tone }) {
    return (
      <div className="hd-tile">
        <span className="hd-tile__label">{label}</span>
        <span className="hd-tile__value">{Math.round(value * 100)}%</span>
        <StockBar percent={value * 100} tone={tone} />
        <span className="hd-footnote">{detail}</span>
        {route ? <Button variant="link" size="xs" onClick={() => onNavigate(route)}>See the rows</Button> : null}
      </div>
    );
  }

  function ReportsScreen({ data, now, viewer, onNavigate, onExport }) {
    const f = reportFigures(data, now);
    const wards = wardRows(data.admissions, data.wardBeds);
    const theatre = interventionsToday(data.interventions, now);
    const open = openAdmissions(data.admissions);
    const longStays = open.filter((a) => ADMISSION_FLAGS.overExpectedStay(a, now));

    return (
      <>
        <PageHeader
          path="/reports"
          title="Reports"
          sub={"Halden General at " + new Date(now).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) + " on " + new Date(now).toLocaleDateString("en-GB", { day: "numeric", month: "long" }) + ". Every rate below states the set it divides, and drills through to it."}
          actions={<ExportMenu scope="These six figures and the rows behind them" onExport={(format) => onExport("Hospital report", "Six figures, " + new Date(now).toLocaleDateString("en-GB", { day: "numeric", month: "short" }), 6, format)} />}
        />

        <Figures three items={[
          { label: "Beds occupied", value: f.occupancy.count + " / " + f.occupancy.of, qualifier: Math.round(f.occupancy.value * 100) + "% of the beds on the " + wards.length + " wards Ward Desk covers" },
          { label: "Mean length of stay", value: f.stay.mean.toFixed(1), qualifier: "days, over the " + f.stay.of + " admissions currently on a ward · longest " + f.stay.longest },
          { label: "Bed waits past four hours", value: f.breaches.count, qualifier: "of " + f.breaches.of + " people waiting for a bed" },
        ]} />

        <Band title="Rates" note="Each rate is a count over a named set, computed at render from the arrays the destination screens use.">
          <div className="hd-split">
            <Rate label="Theatre time booked today" value={Math.min(1, f.theatre.value)} onNavigate={onNavigate} route="/interventions"
              detail={f.theatre.minutes + " minutes across " + f.theatre.cases + " cases, of " + THEATRE_MINUTES_PER_DAY + " minutes across " + THEATRES.length + " rooms"} />
            <Rate label="Consent recorded" value={f.consent.value} onNavigate={onNavigate} route="/interventions"
              tone={f.consent.value < 1 ? "warn" : null}
              detail={f.consent.count + " of " + f.consent.of + " scheduled procedures have consent on the record"} />
            <Rate label="Doses on time" value={f.doses.value} onNavigate={onNavigate} route="/rounds"
              tone={f.doses.value < 1 ? "warn" : null}
              detail={f.doses.count + " of " + f.doses.of + " active courses have no dose more than an hour overdue"} />
            <Rate label="Hospital occupancy" value={f.occupancy.value} onNavigate={onNavigate} route="/wards"
              detail={f.occupancy.count + " of " + f.occupancy.of + " beds, counted from the admissions each ward renders"} />
          </div>
        </Band>

        <div className="hd-cols">
          <div>
            <Band flush fill title={"Occupancy by ward (" + wards.length + ")"} note="Occupied beds against the establishment in each ward's record.">
              <TableWrap>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Ward</TableHead>
                      <TableHead className="hd-num">Occupied</TableHead>
                      <TableHead className="hd-num">Beds</TableHead>
                      <TableHead style={{ minWidth: "8rem" }}>Occupancy</TableHead>
                      <TableHead className="hd-num">Held</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {wards.map((w) => (
                      <TableRow key={w.ward}>
                        <TableCell>
                          <span className="hd-person__text">
                            <span className="hd-person__name"><button type="button" className="hd-linkbtn" onClick={() => onNavigate("/wards")}>{w.label}</button></span>
                            <span className="hd-person__meta">{w.specialty}</span>
                          </span>
                        </TableCell>
                        <TableCell className="hd-num">{w.occupied}</TableCell>
                        <TableCell className="hd-num">{w.beds}</TableCell>
                        <TableCell>
                          <span style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: "7rem" }}>
                            <span className="hd-footnote">{Math.round(w.occupancy * 100)}%</span>
                            <StockBar percent={w.occupancy * 100} tone={w.occupancy > 0.9 ? "warn" : null} />
                          </span>
                        </TableCell>
                        <TableCell className="hd-num">{w.held || <span className="hd-muted">—</span>}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableWrap>
            </Band>
          </div>
          <div className="hd-stack">
            <Band title={"Stays running long (" + longStays.length + ")"} note="On a ward past the stay their admission expected.">
              {longStays.length ? (
                <div className="hd-rows">
                  {longStays.map((admission) => {
                    const patient = patientById(data.patients, admission.patientId);
                    const days = ADMISSION_FLAGS.lengthOfStayDays(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} size={26}
                              meta={wardName(admission.ward) + " " + admission.bed + " · " + staffName(data.staff, admission.consultantId)}
                              onOpen={() => onNavigate("/patients/" + patient.id)} />
                          </span>
                          <span className="hd-row__note">{admission.reason}</span>
                        </div>
                        <Badge size="sm" variant="warning">Day {days} of {admission.expectedStayDays}</Badge>
                      </div>
                    );
                  })}
                </div>
              ) : <p className="hd-footnote">Every open admission is inside the stay it expected.</p>}
            </Band>
            <Band tint title={"Theatre list today (" + theatre.length + ")"} note="What the utilisation figure above is made of.">
              <div className="hd-rows">
                {theatre.map((intervention) => (
                  <div className="hd-row hd-row--quiet" 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">{intervention.plannedMin} min · {labelOf(THEATRES, intervention.theatre)} · {patientName(data.patients, intervention.patientId)}</span>
                    </div>
                    <StatusBadge values={INTERVENTION_STATUS} value={intervention.status} />
                  </div>
                ))}
              </div>
            </Band>
          </div>
        </div>
      </>
    );
  }

  Object.assign(window, { ReportsScreen });
})();
