import { MobileCards } from "../cards/MobileCards";
import { useViewport } from "../hooks/useViewport";
import { getConfig } from "../lib/config";
import { Slot, useProReady } from "../lib/slots";
import { CompareTable } from "./CompareTable";
import { HiddenNote } from "./HiddenNote";
import { EmptyState, ErrorState, LoadingState } from "./States";

/**
 * Picks what to show for a table request: loading, error, empty, the
 * table, or swipe cards on phones and tablets (Phones › layout, or the
 * mount's `layout="cards"`; `layout="table"` always keeps the table).
 * `heading` (inline tables) goes in the table's corner, else above.
 * With Pro, the Pro chunk loads alongside the data (`useProReady`), and
 * the `bulk` slot wraps the table with "Add selected to cart".
 */
export function TableView({
  data,
  error,
  loading,
  reload,
  layout = "auto",
  onlyDiff,
  fromList = false,
  heading = null,
  category = 0,
  setCategory,
}) {
  const viewport = useViewport();
  const mobile = getConfig().mobile || {};
  const proReady = useProReady();

  if (loading || !proReady || error || !data.products.length) {
    return (
      <>
        {heading}
        {loading || !proReady ? (
          <LoadingState />
        ) : error ? (
          <ErrorState error={error} onRetry={reload} />
        ) : (
          <EmptyState />
        )}
      </>
    );
  }

  const wantsCards =
    layout === "cards" || (layout === "auto" && mobile.layout !== "scroll");

  if (viewport !== "desktop" && wantsCards) {
    const columns =
      viewport === "phone"
        ? Number(mobile.columns_phone) || 2
        : Number(mobile.columns_tablet) || 3;

    return (
      <>
        {heading}
        <Slot
          name="tabs"
          data={data}
          active={category}
          onSelect={setCategory}
        />
        <Slot name="bulk" products={data.products}>
          <MobileCards
            data={data}
            columns={Math.min(columns, data.products.length)}
            onlyDiff={onlyDiff}
            fromList={fromList}
          />
        </Slot>
        <Slot name="actions" data={data} fromList={fromList} />
        <HiddenNote data={data} />
      </>
    );
  }

  return (
    <>
      <Slot name="tabs" data={data} active={category} onSelect={setCategory} />
      <Slot name="bulk" products={data.products}>
        <CompareTable
          data={data}
          layout={layout}
          onlyDiff={onlyDiff}
          corner={heading}
          fromList={fromList}
        />
      </Slot>
      <Slot name="actions" data={data} fromList={fromList} />
      <HiddenNote data={data} />
    </>
  );
}
