/* Content — the email templates everything sends.
   Commit model: INSTANT. Publishing and restoring apply immediately with an undo
   toast; archiving is reversible, so it raises an undo toast rather than a
   confirm dialog.
   Data state: one branch — populated, or the no-results branch when the filters
   match nothing.
   Usage is derived, never stored: the "sends it" column reads the journeys and
   broadcasts that point at the template, which is also why a template something
   still sends cannot be archived — the button is refused with the count, not
   hidden.
   Recession (§5.4): an archived template is recessed. It keeps its name, its
   subject and its history; there is simply nothing to do with it. */
(() => {
  const {
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Button, Badge,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  function ContentScreen({ data, now, onNavigate, onContentTransition, onNewTemplate, pushToast }) {
    const [query, setQuery] = React.useState("");
    const [status, setStatus] = React.useState("all");
    const [usage, setUsage] = React.useState("all");
    const { sort, onSort } = useSort("updatedAt");

    const unused = unusedContent(data);
    const inUse = data.content.filter((c) => contentUseCount(c, data) > 0);
    const editedRecently = contentEditedSince(data.content, 30, now);

    const filtered = data.content.filter((item) => {
      if (query && (item.name + " " + item.subject).toLowerCase().indexOf(query.toLowerCase()) === -1) return false;
      if (status !== "all" && item.status !== status) return false;
      if (usage === "used" && contentUseCount(item, data) === 0) return false;
      if (usage === "unused" && contentUseCount(item, data) > 0) return false;
      return true;
    });
    const rows = sortRows(filtered, sort, {
      name: (c) => c.name,
      uses: (c) => contentUseCount(c, data),
      updatedAt: (c) => c.updatedAt,
    });
    const dirty = query !== "" || status !== "all" || usage !== "all";
    const clear = () => { setQuery(""); setStatus("all"); setUsage("all"); };

    return (
      <>
        <PageHeader
          path="/content"
          title="Content"
          actions={
            <>
              <ExportMenu scope={"All " + data.content.length + " templates"} onExport={(format) => pushToast({ title: "Export started", description: data.content.length + " templates · " + format })} />
              <Button size="sm" onClick={onNewTemplate}><Icon name="plus" />New template</Button>
            </>
          }
        />

        <Figures items={[
          {
            label: "Templates",
            value: formatCount(data.content.length),
            qualifier: CONTENT_STATUS.map((s) => data.content.filter((c) => c.status === s.id).length + " " + s.label.toLowerCase()).join(" · "),
          },
          {
            label: "Something sends them",
            value: formatCount(inUse.length),
            qualifier: "Named by a journey step or a broadcast, whatever that journey's state",
          },
          {
            label: "Nothing sends them",
            value: formatCount(unused.length),
            qualifier: unused.length
              ? unused.map((c) => c.name).join(" · ")
              : "Every template is pointed at by something",
          },
          {
            label: "Edited in 30 days",
            value: formatCount(editedRecently.length),
            qualifier: editedRecently.length
              ? "Most recent: " + editedRecently.slice().sort((a, b) => b.updatedAt - a.updatedAt)[0].name
              : "Nothing has been touched this month",
          },
        ]} />

        <section className="md-band md-band--flush">
          <div className="md-band__head">
            <div>
              <h2 className="md-band__title">Every template</h2>
              <p className="md-band__note">What sends a template is read from the journeys and broadcasts that name it, so archiving one that is still in use is refused rather than hidden.</p>
            </div>
          </div>

          <FilterBar
            query={query} onQuery={setQuery} placeholder="Search by name or subject" dirty={dirty} onClear={clear}
            selects={[
              { id: "status", label: "Status", value: status, onChange: setStatus, items: [{ value: "all", label: "Every status" }].concat(CONTENT_STATUS.map((s) => ({ value: s.id, label: s.label }))) },
              { id: "usage", label: "Usage", value: usage, onChange: setUsage, items: [
                { value: "all", label: "Used or not" },
                { value: "used", label: "Something sends it" },
                { value: "unused", label: "Nothing sends it" },
              ] },
            ]}
          />

          {filtered.length === 0 ? (
            <div style={{ padding: "var(--space-6) var(--gutter-page)" }}>
              <Empty>
                <EmptyHeader>
                  <EmptyMedia variant="icon"><Icon name="search-x" size={18} /></EmptyMedia>
                  <EmptyTitle>No template matches those filters</EmptyTitle>
                  <EmptyDescription>Nothing among the {data.content.length} templates in this workspace matches. Widen the filters and try again.</EmptyDescription>
                </EmptyHeader>
                <EmptyContent><Button onClick={clear}>Clear filters</Button></EmptyContent>
              </Empty>
            </div>
          ) : (
            <div className="md-tablewrap">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead><SortHead label="Template" sortKey="name" sort={sort} onSort={onSort} /></TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="md-drop-md"><SortHead label="What sends it" sortKey="uses" sort={sort} onSort={onSort} /></TableHead>
                    <TableHead className="md-num md-drop-lg"><SortHead label="Edited" sortKey="updatedAt" sort={sort} onSort={onSort} /></TableHead>
                    <TableHead className="md-actions-head">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((item) => {
                    const uses = contentUses(item, data);
                    const recessed = CONTENT_FLAGS.isRecessed(item);
                    return (
                      <TableRow key={item.id} className={recessed ? "md-row--recessed" : undefined}>
                        <TableCell>
                          <span className="md-record">
                            <span className="md-record__name">{item.name}</span>
                            <span className="md-record__meta">{item.subject ? "“" + item.subject + "”" : "No subject line yet"}</span>
                          </span>
                        </TableCell>
                        <TableCell><span className="md-status"><StatusBadge values={CONTENT_STATUS} value={item.status} /></span></TableCell>
                        <TableCell className="md-drop-md">
                          {uses.journeys.length === 0 && uses.broadcasts.length === 0 ? <span className="md-muted">Nothing</span> : (
                            <span className="md-chips">
                              {uses.journeys.map((journey) => (
                                <button type="button" key={journey.id} className="md-link" onClick={() => onNavigate("/journeys/" + journey.id)}>
                                  <Badge size="sm" variant="secondary">{journey.name}</Badge>
                                </button>
                              ))}
                              {uses.broadcasts.map((broadcast) => (
                                <button type="button" key={broadcast.id} className="md-link" onClick={() => onNavigate("/broadcasts/" + broadcast.id)}>
                                  <Badge size="sm" variant="secondary">{broadcast.name}</Badge>
                                </button>
                              ))}
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="md-num md-muted md-drop-lg" title={formatAbsolute(item.updatedAt)}>
                          {formatWhen(item.updatedAt, now)}
                          <span className="md-sub">{memberName(data.members, item.updatedById)}</span>
                        </TableCell>
                        <TableCell className="md-actions">
                          <RowActions transitions={contentTransitions(item, uses)} onRun={(t) => onContentTransition(item, t)} label={"Actions for " + item.name} />
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}

          <div className="md-tablefoot">
            <span className="md-footnote">Showing {filtered.length} of {data.content.length} templates.</span>
            <span className="md-footnote">{filtered.filter((c) => contentUseCount(c, data) > 0).length} of the rows shown are sent by something.</span>
          </div>
        </section>
      </>
    );
  }

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