"use client";

import React from "react";

import NameColumn from "./FooterNameColumn";
import PriceColumn from "./FooterPriceColumn";
import type { FormattedPeriod, Item } from "./generateTotal";
import generateTotal from "./generateTotal";

export interface Footer {
  name?: string;
  tooltip?: string;
  hideFirst?: boolean;
}

export interface Labels {
  [key: string]: string;
  remove: string;
  add: string;
  free: string;
  upfront: string;
  monthly: string;
}

export type FooterRow = {
  col1: React.ReactNode;
  col2: React.ReactNode;
  col3: React.ReactNode;
};

function calculateTotal(items: Item[], type: "monthly" | "upfront"): number {
  return items.reduce((total, item) => {
    total += item?.price?.[type] ?? 0;
    total -= item?.discount?.[type] ?? 0;
    return total;
  }, 0);
}

const generateFooter = (
  items: Item[],
  hide: string,
  footer: Footer,
  labels: Labels,
  size: "large",
): FooterRow[] => {
  const hasLimitedDiscounts = items.find(
    (item) => item?.monthsFree || item?.discount?.monthsCount,
  );
  if (hasLimitedDiscounts) {
    const total = generateTotal(items, footer?.hideFirst) as FormattedPeriod[];
    return total.map(({ name, price, discount }) => ({
      col1: <NameColumn name={name} tooltip={footer?.tooltip} />,
      col2: price &&
        price.upfront !== undefined &&
        price.upfront > 0 &&
        hide !== "upfront" && (
          <PriceColumn
            price={price.upfront}
            discount={discount && discount.upfront}
            label={labels["upfront"]}
            size={size}
          />
        ),
      col3: (
        <PriceColumn
          price={price.monthly}
          discount={discount && discount.monthly}
          label={labels["monthly"]}
          size={size}
        />
      ),
    }));
  }
  return [
    {
      col1: footer?.name && (
        <NameColumn name={footer.name} tooltip={footer.tooltip} />
      ),
      col2: hide !== "upfront" && (
        <PriceColumn
          price={calculateTotal(items, "upfront")}
          label={labels["upfront"]}
          size={size}
        />
      ),
      col3: (
        <PriceColumn
          price={calculateTotal(items, "monthly")}
          label={labels["monthly"]}
          size={size}
        />
      ),
    },
  ];
};

export default generateFooter;
