"use client";

import cx from "classnames";
import React from "react";

import { capitalize } from "../../utils";
import { Table } from "../Table";
import type { Footer, Labels } from "./generateFooter";
import generateFooter from "./generateFooter";
import generateRow from "./generateRow";
import type { Item } from "./generateTotal";

const CLASS_ROOT = "cart-table";

export interface CartTableProps {
  footer?: Footer;
  hideEmpty?: boolean;
  isEditable?: boolean;
  items: Item[];
  labels?: Labels;
  size?: "large";
}

const defaultLabels: Labels = {
  monthly: "mesačne",
  upfront: "vopred",
  product: "produkt",
  remove: "odstrániť",
  add: "Pridať",
  install: "inštalácia",
  free: "zadarmo",
};

const CartTable: React.FC<CartTableProps> = ({
  items = [],
  hideEmpty = true,
  isEditable = false,
  footer,
  labels = defaultLabels,
  size,
}) => {
  const hideClass = hideEmpty ? [" hide", " hide"] : ["", ""];

  if (hideEmpty) {
    items.forEach(({ price = {}, discount = {} }) => {
      if (price.upfront !== undefined || discount.upfront !== undefined) {
        hideClass[0] = "";
      }
      if (price.monthly !== undefined || discount.monthly !== undefined) {
        hideClass[1] = "";
      }
    });
  }

  return (
    <Table
      className={cx(CLASS_ROOT, {
        [`${CLASS_ROOT}--large`]: size,
      })}
      headers={[
        {
          key: "col1",
          cellProps: {
            className: "cart-table__product",
          },
          label: capitalize(labels.product),
        },
        {
          cellProps: {
            className: `align-right ${CLASS_ROOT}__price${hideClass[0]}`,
          },
          key: "col2",
          label: capitalize(labels.upfront),
        },
        {
          cellProps: {
            className: `align-right ${CLASS_ROOT}__price${hideClass[1]}`,
          },
          key: "col3",
          label: capitalize(labels.monthly),
        },
        ...(isEditable
          ? [
              {
                cellProps: {
                  className: "align-right",
                },
                key: "col4",
                label: "",
              },
            ]
          : []),
      ]}
      rows={items.map((row) => ({
        ...generateRow(row, isEditable, labels),
      }))}
      footers={generateFooter(
        items,
        "true",
        footer ?? {},
        labels,
        size === "large" ? "large" : (undefined as never),
      )}
    ></Table>
  );
};

CartTable.displayName = "CartTable";

export { CartTable };
