"use client";

import { ReactNode, useCallback, useMemo } from "react";
import { useTranslations } from "next-intl";

import { Button, Typography } from "@/components/ui";
import { Table } from "@/components/widgets";
import { UserSubscription } from "@/entities/subscriptions/types";
import { formatDate } from "@/shared/utils/date";
import { getFormattedPrice } from "@/shared/utils/price";
import { Currency } from "@/types";

import { useCancelSubscriptionModal } from "../CancelSubscriptionModalProvider/CancelSubscriptionModalProvider";

import styles from "./SubscriptionTable.module.scss";

interface ITableProps {
  subscription: UserSubscription;
}

export default function SubscriptionTable({ subscription }: ITableProps) {
  const t = useTranslations("Subscriptions");
  const { open } = useCancelSubscriptionModal();

  const getSubscriptionStatusText = useCallback(() => {
    if (subscription.subscriptionStatus === "CANCELLED") {
      if (subscription.cancellationDate) {
        const formattedDate = formatDate(subscription.cancellationDate);
        if (formattedDate) {
          return t(
            `table.subscription_status_value.${subscription.subscriptionStatus}`,
            {
              date: formattedDate,
            }
          );
        }
      }
      return "Cancelled";
    }
    return t(
      `table.subscription_status_value.${subscription.subscriptionStatus}`
    );
  }, [subscription.subscriptionStatus, subscription.cancellationDate, t]);

  const tableData: ReactNode[][] = useMemo(() => {
    const data: ReactNode[][] = [
      [
        t("table.subscription_type"),
        t(`table.subscription_type_value.${subscription.subscriptionType}`),
      ],
      [t("table.subscription_status"), getSubscriptionStatusText()],
      [
        t("table.billing_period"),
        t(`table.billing_period_value.${subscription.billingPeriod}`),
      ],
      [t("table.last_payment_on"), formatDate(subscription.lastPaymentOn)],
      [t("table.renewal_date"), formatDate(subscription.renewalDate)],
      [
        t("table.renewal_amount"),
        getFormattedPrice(
          subscription.renewalAmount,
          Currency[subscription.currency]
        ),
      ],
    ];

    if (subscription.subscriptionStatus === "ACTIVE") {
      data.push([
        <Button
          key={"cancel-subscription"}
          className={styles.buttonCancel}
          onClick={() => open(subscription)}
        >
          <Typography color="muted" className={styles.buttonCancelText}>
            {t("table.cancel_subscription")}
          </Typography>
        </Button>,
      ]);
    }

    return data;
  }, [subscription, t, open, getSubscriptionStatusText]);

  return <Table data={tableData} />;
}
