import { useOnlyDiff } from "../hooks/useOnlyDiff";
import { useTable } from "../hooks/useTable";
import { getConfig } from "../lib/config";
import { summary } from "../lib/summary";
import { ClearAllButton } from "./ClearAllButton";
import { OnlyDiffSwitch } from "./OnlyDiffSwitch";
import { RelatedStrip } from "./RelatedStrip";
import { ShareActions } from "./ShareActions";
import { ShareCard } from "./ShareCard";
import { SharedExpired, SharedNotice } from "./SharedNotice";
import { TableHeading } from "./TableHeading";
import { TableView } from "./TableView";

/**
 * Root of one inline table (compare page, block). A shared link whose
 * products are all gone never falls back to the visitor's own list.
 */
export function TableApp(props) {
  if (props.shared && !props.ids.length) {
    return <SharedExpired />;
  }

  return <InlineTable {...props} />;
}

/**
 * Toolbar (summary, Share, Print, "Only differences", Clear all on the
 * shopper's own list), the table, suggestions and the share card. A quick
 * table (product page) keeps only the "Only differences" switch.
 */
function InlineTable({
  ids,
  fields,
  context,
  layout,
  onlyDiffToggle,
  shared,
  title,
  pinned,
  onlyDiff: startDiff = null,
}) {
  const table = useTable({ ids, fields, context, pinned });
  const [onlyDiff, toggle] = useOnlyDiff(
    startDiff ?? Boolean(table.data && table.data.only_diff_default),
  );
  const products = table.data ? table.data.products : [];
  const own = !ids.length && !shared;
  const quick = context === "quick";
  const canToggle =
    onlyDiffToggle &&
    getConfig().table.show_only_differences_toggle !== false &&
    products.length > 1;

  return (
    <>
      {shared && <SharedNotice />}
      {products.length > 0 && (
        <div className="pcfw-table__toolbar">
          {!quick && (
            <span className="pcfw-table__count">
              {summary(table.data, Number(getConfig().limit) || 4)}
            </span>
          )}
          <div className="pcfw-table__tools">
            {!quick && <ShareActions products={products} />}
            {canToggle && (
              <OnlyDiffSwitch checked={onlyDiff} onToggle={toggle} />
            )}
            {own && <ClearAllButton />}
          </div>
        </div>
      )}
      <TableView
        {...table}
        layout={layout}
        onlyDiff={canToggle && onlyDiff}
        fromList={own}
        heading={
          <TableHeading title={title} description={quick ? "" : undefined} />
        }
      />
      {own && <RelatedStrip data={table.data} />}
      {own && <ShareCard products={products} />}
    </>
  );
}
