import Title from "@/components/Title"
import styles from "./styles.module.scss"
import Table from "../../components/Table"
import { ReactNode, useCallback, useMemo, useState } from "react"
import Modal from "@/components/Modal"
import Button from "@/components/CompatibilityV2/components/Button"
import { useTranslations } from "@/hooks/translations"
import { addCurrency, ELocalesPlacement } from "@/locales"
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useApi, useApiCall, UserSubscriptions } from "@/api"
import { useDispatch, useSelector } from "react-redux"
import { actions, selectors } from "@/store"
import Loader from "@/components/Loader"
import { getFormattedPrice } from "@/utils/price.utils"
import { Currency } from "@/components/PaymentTable"



const formatDate = (date: string | null) => {
  if (!date) return null;
  return new Date(date).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
};


function SubscriptionsPage() {
  const dispatch = useDispatch();
  const { translate } = useTranslations(ELocalesPlacement.Profile);
  const navigate = useNavigate();
  const api = useApi();
  const token = useSelector(selectors.selectToken);

  const [cancelSubscriptionModal, setCancelSubscriptionModal] = useState(false);

  const subscriptionsData = useCallback(async () => {
    const subscriptions = await api.getUserSubscriptions({
      token
    });
    return subscriptions;
  }, [api]);

  const { data: userSubscriptions, isPending } =
    useApiCall<UserSubscriptions.ResponseGet>(subscriptionsData);

  // const isError = useMemo(() => {
  //   return !isPending && !userSubscriptions?.data?.length;
  // }, [isPending, userSubscriptions?.data]);

  const handleCancelSubscriptionModal = (subscriptionId: string) => {
    dispatch(actions.retainingFunnel.setCancellingSubscriptionId(subscriptionId));
    setCancelSubscriptionModal(true);
  };

  const handleCancelSubscription = () => {
    navigate(routes.client.retainingFunnelCancelSubscription());
    setCancelSubscriptionModal(false);
  };

  const data = useMemo(() => {
    return userSubscriptions?.data?.map(subscription => {
      const tableData: ReactNode[][] = [
        [translate("/subscriptions.table.subscription_type"), translate(`/subscriptions.table.subscription_type_value.${subscription.subscriptionType}`)],
        [translate("/subscriptions.table.subscription_status"), translate(`/subscriptions.table.subscription_status_value.${subscription.subscriptionStatus}`, {
          date: formatDate(subscription.cancellationDate)
        })],
        [translate("/subscriptions.table.billing_period"), translate(`/subscriptions.table.billing_period_value.${subscription.billingPeriod}`)],
        [translate("/subscriptions.table.last_payment_on"), formatDate(subscription.lastPaymentOn)],
        [translate("/subscriptions.table.renewal_date"), formatDate(subscription.renewalDate)],
        [translate("/subscriptions.table.renewal_amount"), addCurrency(getFormattedPrice(subscription.renewalAmount), Currency[subscription.currency])],
      ]
      if (subscription.subscriptionStatus === "ACTIVE") {
        tableData.push([
          <Button className={styles.buttonCancel} onClick={() => handleCancelSubscriptionModal(subscription.id)}>
            {translate("/subscriptions.table.cancel_subscription")}
          </Button>
        ])
      }
      return tableData;
    })
  }, [translate, userSubscriptions?.data])

  if (isPending) {
    return <Loader />
  }

  if (userSubscriptions?.data?.length === 0) {
    return <div className={styles.container}>
      <Title variant="h1" className={styles.title}>{translate("/subscriptions.title")}</Title>
      <p className={styles.description}>{translate("/subscriptions.no_subscriptions")}</p>
    </div>
  }

  // if (isError) {
  //   return <div className={styles.container}>
  //     <Title variant="h1" className={styles.title}>{translate("/subscriptions.title")}</Title>
  //     <p className={styles.error}>{translate("/subscriptions.error")}</p>
  //   </div>
  // }

  return (
    <div className={styles.container}>
      <Title variant="h1" className={styles.title}>{translate("/subscriptions.title")}</Title>
      {data?.length &&
        data.map((subscription, index) => {
          return <Table data={subscription} key={index} />
        })
      }
      {cancelSubscriptionModal && <Modal
        isCloseButtonVisible={false}
        open={!!cancelSubscriptionModal}
        onClose={() => setCancelSubscriptionModal(false)}
        className={styles.modal}
        containerClassName={styles["modal-container"]}
      >
        <Title variant="h4" className={styles["modal-title"]}>
          {translate("/subscriptions.modal.title")}
        </Title>
        <p className={styles["modal-description"]}>
          {translate("/subscriptions.modal.description")}
        </p>
        <div className={styles["modal-answers"]}>
          <div className={styles["modal-answer"]} onClick={handleCancelSubscription}>
            <p className={styles["modal-answer-text"]}>
              {translate("/subscriptions.modal.cancel_button")}
            </p>
          </div>
          <div className={styles["modal-answer"]} onClick={() => setCancelSubscriptionModal(false)}>
            <p className={styles["modal-answer-text"]}>
              {translate("/subscriptions.modal.stay_button")}
            </p>
          </div>
        </div>
      </Modal>}
    </div>
  )
}

export default SubscriptionsPage