import React, { useEffect, useState } from "react";
import "./Subscription.css";
import CButton from "../../components/CButton";
import { useTranslation } from "react-i18next";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import {
  fetchPaymentMethods,
  fetchTariffs,
  pay,
} from "../../stores/slices/billingSlice";
import type { IPaymentMethod, ITariff } from "../../types/billing.types";
import CLoading from "../../components/CLoading";

const Subscription: React.FC = () => {
  const [selectedTariff, setSelectedTariff] = useState<ITariff | null>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] =
    useState<IPaymentMethod | null>(null);
  const {
    tariffs,
    paymentMethods,
    isTariffsLoading,
    isPaymentMethodsLoading,
    payUrl,
    isPayLoading,
  } = useAppSelector((state: RootState) => state.billing);
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  useEffect(() => {
    dispatch(fetchTariffs());
    dispatch(fetchPaymentMethods());
  }, [dispatch]);

  useEffect(() => {
    if (tariffs.length > 0) {
      setSelectedTariff(tariffs[0]);
    }
  }, [tariffs]);

  useEffect(() => {
    if (paymentMethods.length > 0) {
      setSelectedPaymentMethod(paymentMethods[0]);
    }
  }, [paymentMethods]);

  useEffect(() => {
    if (payUrl) {
      window.location.href = payUrl;
    }
  }, [payUrl]);

  const handlePay = () => {
    if (!selectedTariff || !selectedPaymentMethod) {
      return;
    }

    dispatch(
      pay({
        paymentMethodId: selectedPaymentMethod.id,
        payMonths: selectedTariff.payMonths,
      })
    );
  };

  return (
    <div className="subscription wrapper">
      {isTariffsLoading &&
        isPaymentMethodsLoading &&
        tariffs.length === 0 &&
        paymentMethods.length === 0 && (
          <div className="cloading__center">
            <CLoading />
          </div>
        )}

      <div className="subscription__tariffs">
        <h3 className="subscription__tariffs__title">
          {t("subscription.selectTariff")}
        </h3>

        <div className="subscription__tariffs__list">
          {tariffs.map((tariff) => (
            <div
              key={tariff.id}
              className={`subscription__tariff ${
                selectedTariff?.id === tariff?.id
                  ? "subscription__tariff-selected"
                  : ""
              }`}
              onClick={() => setSelectedTariff(tariff)}
            >
              <h4 className="subscription__tariff__title">{tariff.title}</h4>
              <p className="subscription__tariff__amount">${tariff.amount}</p>
            </div>
          ))}
        </div>
      </div>

      <div className="subscription__payments">
        <h3 className="subscription__payments__title">
          {t("subscription.selectPaymentMethod")}
        </h3>

        <div className="subscription__payments__list">
          {paymentMethods.map((method) => (
            <div
              key={method.id}
              className={`subscription__payment ${
                selectedPaymentMethod?.id === method?.id
                  ? "subscription__payment-selected"
                  : ""
              }`}
              onClick={() => setSelectedPaymentMethod(method)}
            >
              <img
                src={`https://cabinet.thecybernanny.com/new/payicons/${method.icon}`}
                alt={method.icon}
                className="subscription__payment__icon"
              />
              <p className="subscription__payment__name">{method.name}</p>
            </div>
          ))}
        </div>
      </div>

      <CButton
        title={t("subscription.pay")}
        onClick={handlePay}
        isLoading={isPayLoading}
      />
    </div>
  );
};

export default Subscription;
