/* Capture: Class summary.
 *
 * Post-save, runs the smart-link suggestion: parse the transcript for
 * member names and offer them as one-tap chips. Confirmed names are
 * appended to the entry's `members` array via an entry update.
 */
(function () {
  const { useState, useEffect } = React;
  const { CaptureFlow, Drawer, Button, Pill, fb, api, members, showToast, tokens } =
    window.CC;

  function CaptureClass({ open, onClose, onSaved }) {
    // After the entry saves, capture the saved entry so we can run the
    // smart-link suggestion against the persisted transcript.
    const [smartLinkFor, setSmartLinkFor] = useState(null);

    useEffect(() => {
      if (open) setSmartLinkFor(null);
    }, [open]);

    function handleSaved(entry) {
      // Try to find member name candidates from the transcript.
      const candidates = api.suggestMemberMentions(
        entry.transcript || entry.body,
        members.all()
      );
      if (candidates.length === 0) {
        onSaved?.(entry);
        return;
      }
      setSmartLinkFor({ entry, candidates });
    }

    return (
      <>
        <CaptureFlow
          open={open && !smartLinkFor}
          onClose={onClose}
          type="class"
          title="Class summary"
          placeholder="How did the class go?"
          onSaved={handleSaved}
        />
        {smartLinkFor && (
          <SmartLinkSheet
            entry={smartLinkFor.entry}
            candidates={smartLinkFor.candidates}
            onDone={() => {
              const e = smartLinkFor.entry;
              setSmartLinkFor(null);
              onSaved?.(e);
              onClose?.();
            }}
          />
        )}
      </>
    );
  }

  function SmartLinkSheet({ entry, candidates, onDone }) {
    const [picks, setPicks] = useState(() => candidates.map((c) => c.row_id));
    const [saving, setSaving] = useState(false);

    function toggle(id) {
      setPicks((p) =>
        p.includes(id) ? p.filter((x) => x !== id) : [...p, id]
      );
    }

    async function confirm() {
      setSaving(true);
      try {
        if (picks.length > 0) {
          await fb.update(`entries/${entry.id}`, { members: picks });
          showToast(
            `Tagged ${picks.length} member${picks.length === 1 ? "" : "s"}.`
          );
        }
      } catch (e) {
        console.warn(e);
      }
      setSaving(false);
      onDone();
    }

    return (
      <Drawer
        open
        onClose={onDone}
        title="Tag members?"
        footer={
          <Button fullWidth size="lg" onClick={confirm} loading={saving}>
            {picks.length === 0 ? "Skip" : `Tag ${picks.length}`}
          </Button>
        }
      >
        <p
          style={{
            margin: 0,
            color: tokens.colors.textMuted,
            fontSize: 14,
          }}
        >
          We spotted these names in your summary. Tap to confirm.
        </p>
        <div
          style={{
            display: "flex",
            flexWrap: "wrap",
            gap: 8,
            marginTop: 16,
          }}
        >
          {candidates.map((m) => {
            const on = picks.includes(m.row_id);
            return (
              <button
                key={m.row_id}
                type="button"
                onClick={() => toggle(m.row_id)}
                className="cc-link-chip"
                aria-pressed={on}
                style={{
                  background: on ? tokens.colors.primary : tokens.colors.surface,
                  color: on ? "#fff" : tokens.colors.text,
                  borderColor: on ? tokens.colors.primary : tokens.colors.border,
                }}
              >
                <Pill size="sm" tone={tokens.statusForLabel(m.status)}>
                  {m.status}
                </Pill>
                <span>{m.name}</span>
              </button>
            );
          })}
        </div>
      </Drawer>
    );
  }

  window.CC = window.CC || {};
  window.CC.CaptureClass = CaptureClass;
})();
