/* Routines — what the house does on its own.
   Commit model: INSTANT. Running, pausing and resuming apply immediately with an
   undo toast; finishing a draft and fixing a broken routine each need two
   decisions, so they open a staged dialog; deleting one confirms.

   Three sections, each running its own predicate: what wants a person, what is
   running, what is paused. A broken routine is stated at full weight — the house
   is quietly not doing something — while a paused one is recessed, because it is
   waiting on a decision rather than on work. */
(() => {
  const { Button, Badge, Alert, AlertTitle, AlertDescription } = window.OriginDesignSystem_7c998b;

  function RoutineRow({ routine, data, now, viewer, onRoutineTransition, onNavigate }) {
    const devices = routine.deviceIds.map((id) => deviceById(data.devices, id)).filter(Boolean);
    const member = routine.memberId ? memberById(data.members, routine.memberId) : null;
    return (
      <Row recessed={routine.recessed}
        title={
          <>
            {routine.name}
            <StatusBadge values={ROUTINE_STATUS} value={routine.status} />
            {routine.broken ? <Badge size="sm" variant="warning">Broken</Badge> : null}
          </>
        }
        note={
          routine.broken
            ? "It names " + routine.missing.map((id) => deviceName(data.devices, id)).join(" and ") + ", which is not in the house — so it has not run since " + formatWhen(routine.lastRunAt, now) + "."
            : labelOf(TRIGGER_KINDS, routine.trigger)
              + (routine.when ? " · " + routine.when : "")
              + (member ? " · reads " + member.name.split(" ")[0] + "'s own bedtime" : "")
              + (routine.offsetMinutes ? " · " + Math.abs(routine.offsetMinutes) + " minutes " + (routine.offsetMinutes < 0 ? "before" : "after") : "")
        }
        meta={
          devices.map((d) => d.name.toLowerCase()).join(", ")
          + " · ran " + formatCount(routine.runs) + " times, last " + formatWhen(routine.lastRunAt, now)
        }>
        <RowActions transitions={routineTransitions(routine, data.devices, viewer)} onRun={(t) => onRoutineTransition(routine, t)} label={"Actions for " + routine.name} />
      </Row>
    );
  }

  function RoutinesScreen({ data, now, viewer, onNavigate, onRoutineTransition, onNewRoutine, onExport }) {
    const rows = routineRows(data, now);
    const needy = routinesNeedingYou(rows);
    const running = routinesRunning(rows);
    const paused = routinesPaused(rows);
    const target = comfortTarget(data.members, now);

    return (
      <>
        <PageHead path="/routines" title="Routines"
          lede={running.length + " routines run on their own. " + (needy.length ? needy.length + " want a person — a routine that names a device which has left the house is broken, and nothing had to be written on it for that to be true." : "None of them is broken.")}
          actions={
            <>
              <ExportMenu scope={"All " + rows.length + " routines"} onExport={(format) => onExport("Routines", "Every routine", rows.length, format)} />
              <Button size="sm" onClick={onNewRoutine}><Icon name="plus" />New routine</Button>
            </>
          } />

        <Figures items={[
          { label: "Running", value: running.length, unit: "of " + rows.length, qualifier: running.filter((r) => r.trigger === "presence").length + " on presence, " + running.filter((r) => r.trigger === "time").length + " on a clock, " + running.filter((r) => r.trigger === "sunset").length + " on sunset" },
          { label: "Wanting a person", value: needy.length, qualifier: needy.filter((r) => r.broken).length + " broken, " + needy.filter((r) => r.status === "draft").length + " never finished" },
          { label: "Times they have run", value: formatCount(rows.reduce((n, r) => n + r.runs, 0)), qualifier: "most of it " + rows.slice().sort((a, b) => b.runs - a.runs)[0].name.toLowerCase() },
          { label: "Reading a person", value: rows.filter((r) => r.memberId).length, qualifier: "they store the person, not the time, so moving a bedtime moves the routine" },
        ]} />

        {needy.length ? (
          <Band>
            <Card flush title={"Wanting a person (" + needy.length + ")"} note="Unfinished, or naming a device that is no longer in the house.">
              <div style={{ paddingInline: "var(--card-pad)" }}>
                <Rows>
                  {needy.map((routine) => (
                    <RoutineRow key={routine.id} routine={routine} data={data} now={now} viewer={viewer}
                      onRoutineTransition={onRoutineTransition} onNavigate={onNavigate} />
                  ))}
                </Rows>
              </div>
            </Card>
          </Band>
        ) : null}

        <div className="hh-cols hh-cols--wide">
          <div>
            <Card flush title={"Running (" + running.length + ")"} note="On, and every device they name is still in the house.">
              <div style={{ paddingInline: "var(--card-pad)" }}>
                <Rows>
                  {running.map((routine) => (
                    <RoutineRow key={routine.id} routine={routine} data={data} now={now} viewer={viewer}
                      onRoutineTransition={onRoutineTransition} onNavigate={onNavigate} />
                  ))}
                </Rows>
              </div>
            </Card>

            {paused.length ? (
              <Card flush title={"Paused (" + paused.length + ")"} note="Waiting on a decision rather than on work, so they are recessed.">
                <div style={{ paddingInline: "var(--card-pad)" }}>
                  <Rows>
                    {paused.map((routine) => (
                      <RoutineRow key={routine.id} routine={routine} data={data} now={now} viewer={viewer}
                        onRoutineTransition={onRoutineTransition} onNavigate={onNavigate} />
                    ))}
                  </Rows>
                </div>
              </Card>
            ) : null}
          </div>

          <div>
            <Card title="What the routines read" note="None of these numbers is stored on a routine; each one is read when it runs.">
              <Rows>
                <Row title="The comfort target" value={formatTemp(target.c) + "°"}
                  note={"Nobody home and awake means " + formatTemp(HOUSE_POLICY.awaySetbackC) + "° · everybody asleep means " + formatTemp(HOUSE_POLICY.nightSetbackC) + "°"} />
                <Row title="Sunset" value={HOUSE_POLICY.darkAfter}
                  note={"Evening lights runs 20 minutes before · " + (isDark(now) ? "dark now" : "still light")} />
                <Row title="Off-peak window" value={tariffWindow("off_peak").from}
                  note={"The battery routine starts here, at " + tariffWindow("off_peak").pencePerKwh + "p"} />
                <Row title="Quiet hours" value={HOUSE_POLICY.quietFrom + "–" + HOUSE_POLICY.quietTo}
                  note="Nothing pushes or rings between these" />
                {data.members.filter((m) => routinesForMember(rows, m.id).length).map((member) => (
                  <Row key={member.id} title={member.name.split(" ")[0] + "'s bedtime"} value={member.prefs.bedtime}
                    note={<>Set on <button type="button" className="hh-linkbtn" onClick={() => onNavigate("/people/" + member.id)}>their own screen</button> · {routinesForMember(rows, member.id).map((r) => r.name.toLowerCase()).join(", ")}</>} />
                ))}
              </Rows>
            </Card>

            <Card tint title="Triggers the house understands" note="What a new routine can be built on.">
              <Rows>
                {TRIGGER_KINDS.map((trigger) => (
                  <Row key={trigger.value} title={trigger.label}
                    value={rows.filter((r) => r.trigger === trigger.value).length}
                    note={rows.filter((r) => r.trigger === trigger.value).map((r) => r.name.toLowerCase()).join(", ") || "nothing uses it yet"} />
                ))}
              </Rows>
            </Card>
          </div>
        </div>
      </>
    );
  }

  Object.assign(window, { RoutinesScreen, RoutineRow });
})();
