'use client';

import { useState } from 'react';
import type { SalesDesignGroup, SalesReportInfo, SalesReportResult } from '../api.client';
import {
  DESIGN_GROUPS,
  QUICK_ANSWERS_SHOWN,
  SALES_QUICK_ANSWERS,
  SALES_SUGGESTED_REPORTS,
  defaultRange,
  designGroupOf,
  isListedReport,
  reportIcon,
} from '../constants';
import { formatFigure } from '../format';
import { pctDelta } from '../model';
import { rangeText } from '../ranges';
import { EmptyArt, NO_DATA, SaFill, SaIcon } from './icons';

/** A card's result, or the error it gave. */
export type CardResult = SalesReportResult | string;

/** The suite home (design `paintHome`) or a group page (`paintGroup`). */
export function SalesHome({
  catalog,
  cards,
  recent,
  group,
  search,
  onOpen,
  onHome,
}: {
  catalog: SalesReportInfo[];
  cards: Record<string, CardResult>;
  recent: string[];
  group: SalesDesignGroup | null;
  search: string;
  onOpen: (key: string) => void;
  onHome: () => void;
}) {
  const [quickAll, setQuickAll] = useState(false);
  const byKey = new Map(catalog.map((r) => [r.key, r]));
  // LP9: a second tab is opened from its first tab, not listed.
  const listed = catalog.filter(isListedReport);
  const inGroup = group ? listed.filter((r) => designGroupOf(r) === group) : listed;
  const list = inGroup.filter(
    (r) => !search || `${r.title} ${r.description}`.toLowerCase().includes(search),
  );
  const recentShown = recent
    .filter((k) => byKey.has(k) && (!group || designGroupOf(byKey.get(k)!) === group))
    .slice(0, 4);
  const quick = SALES_QUICK_ANSWERS.filter((x) => byKey.has(x.key));
  const quickShown = quickAll ? quick : quick.slice(0, QUICK_ANSWERS_SHOWN);
  const suggested = SALES_SUGGESTED_REPORTS.filter((k) => byKey.has(k));
  const groupLabel = DESIGN_GROUPS.find((g) => g.key === group)?.label;

  const tile = (key: string) => {
    const r = byKey.get(key)!;
    return (
      <button key={key} type="button" className="sa-tile" onClick={() => onOpen(key)}>
        <SaIcon name={reportIcon(key)} />
        <span>{r.title}</span>
      </button>
    );
  };

  const cardsSection = (
    <section aria-labelledby="saRmH">
      <h2 className="sa-h2" id="saRmH">
        Ready-made reports
      </h2>
      {list.length ? (
        <div className="sa-cards">
          {list.map((r) => (
            <ReportCard key={r.key} info={r} result={cards[r.key]} onOpen={onOpen} />
          ))}
        </div>
      ) : (
        <p className="sa-muted">No reports match &quot;{search}&quot;.</p>
      )}
    </section>
  );

  if (group) {
    return (
      <div className="sa-home sa-grp">
        <div className="sa-intro">
          <nav className="sa-crumbs" aria-label="Breadcrumb">
            <button type="button" className="sa-link" onClick={onHome}>
              Sales analytics suite
            </button>
            <span aria-hidden="true">›</span>
            <span aria-current="page">{groupLabel}</span>
          </nav>
          <h1 className="sa-h1">{groupLabel}</h1>
        </div>
        {recentShown.length ? (
          <section aria-labelledby="saRvH">
            <h2 className="sa-h2" id="saRvH">
              Recently viewed
            </h2>
            <div className="sa-tiles">{recentShown.map(tile)}</div>
          </section>
        ) : null}
        {cardsSection}
      </div>
    );
  }

  return (
    <div className="sa-home">
      <div className="sa-intro">
        <h2 className="sa-h1">Sales analytics suite</h2>
        <p className="sa-muted">Ready-made sales reports based on best practices</p>
      </div>
      {quick.length ? (
        <section className="sa-qa" aria-labelledby="saQaH">
          <div className="sa-qa__head">
            <h3 id="saQaH" className="sa-qa__k">
              QUICK ANSWERS
            </h3>
            <span className="sa-qa__pop">
              <SaIcon name="flame" className="sa-i--sm" />
              Most popular
            </span>
            {quick.length > QUICK_ANSWERS_SHOWN ? (
              <button
                type="button"
                className="sa-link sa-qa__all"
                aria-expanded={quickAll}
                onClick={() => setQuickAll((v) => !v)}
              >
                {quickAll ? 'See less' : `See all (${quick.length})`}
                <SaIcon
                  name={quickAll ? 'caret' : 'down'}
                  className={quickAll ? 'sa-i--sm sa-flip' : 'sa-i--sm'}
                />
              </button>
            ) : null}
          </div>
          <div className="sa-qa__chips">
            {quickShown.map((x) => (
              <button
                key={x.question}
                type="button"
                className="sa-qchip"
                onClick={() => onOpen(x.key)}
              >
                <SaIcon name="flame" className="sa-i--sm" />
                {x.question}
              </button>
            ))}
          </div>
        </section>
      ) : null}
      {recentShown.length ? (
        <section aria-labelledby="saRvH">
          <h2 className="sa-h2" id="saRvH">
            Recently viewed
          </h2>
          <div className="sa-tiles">{recentShown.map(tile)}</div>
        </section>
      ) : null}
      {suggested.length ? (
        <section aria-labelledby="saSgH">
          <h2 className="sa-h2" id="saSgH">
            Suggested for you <span className="sa-beta">Beta</span>
          </h2>
          <div className="sa-tiles">{suggested.map(tile)}</div>
        </section>
      ) : null}
      {cardsSection}
    </div>
  );
}

/** A ready-made report card with its figure for its default range (design `card` / `preview`). */
function ReportCard({
  info,
  result,
  onOpen,
}: {
  info: SalesReportInfo;
  result: CardResult | undefined;
  onOpen: (key: string) => void;
}) {
  const chip = <span className="sa-chip">{rangeText(defaultRange(info.key))}</span>;
  let preview: React.ReactNode;
  if (result === undefined) {
    preview = (
      <div className="sa-card__pv">
        {chip}
        <p className="sa-muted">Loading…</p>
      </div>
    );
  } else if (typeof result === 'string') {
    preview = (
      <div className="sa-card__pv">
        {chip}
        <p className="sa-muted">This report could not be loaded.</p>
      </div>
    );
  } else if (!result.rows.length) {
    preview = (
      <div className="sa-card__pv">
        {chip}
        <EmptyArt />
        <p className="sa-muted">{NO_DATA}</p>
      </div>
    );
  } else if (result.total === null) {
    preview = (
      <div className="sa-card__pv sa-card__pv--txt">
        <p>
          <strong>Can&apos;t be summarized.</strong>
        </p>
        <p>View this report to explore your data.</p>
      </div>
    );
  } else {
    const d = result.previous ? pctDelta(result.total, result.previous.total) : null;
    preview = (
      <div className="sa-card__pv">
        {chip}
        <p className="sa-kpi__l">{info.columns.value}</p>
        <p className="sa-kpi__v">{formatFigure(result.total, info.unit, result.currency)}</p>
        {d !== null ? <Delta d={d} /> : null}
      </div>
    );
  }
  return (
    <article className="sa-card">
      <h3 className="sa-card__t">
        <button type="button" className="sa-card__btn" onClick={() => onOpen(info.key)}>
          <SaIcon name={reportIcon(info.key)} />
          <span>{info.title}</span>
        </button>
      </h3>
      <p className="sa-card__d">{info.description}</p>
      {preview}
    </article>
  );
}

/** The change against the previous period, up or down (design `deltaHtml`). */
export function Delta({ d }: { d: number | null }) {
  if (d === null) return <p className="sa-delta sa-muted">–</p>;
  const up = d >= 0;
  return (
    <p className={`sa-delta ${up ? 'is-up' : 'is-dn'}`}>
      <SaFill name={up ? 'up' : 'dn'} />
      <span className="sa-sr">{up ? 'Up' : 'Down'} </span>
      {Math.abs(+d.toFixed(2))}%
    </p>
  );
}
