import React, { useCallback, useEffect, useState } from "react";

import { PAYMENTS_TYPE } from "../../constants/app";
import { usePayments } from "../../hooks/usePayments";
import { useUserStore } from "../../stores/userStore";
import { PaymentsMethod, PaymentType } from "../../types/payments";
import WalletTermsAndConditionComponent from "./WalletTermsAndConditionComponent";

type WalletSectionManagerProps = {
  paymentMethodData: PaymentsMethod;
  activeTab: boolean;
  setDisablePaymentButton: (status: boolean) => void;
  type?: PaymentType;
  PaybyWalletComponent: React.ComponentType<{
    assets: any;
    paymentMethodData: PaymentsMethod;
    setDisablePaymentButton: (status: boolean) => void;
  }>;
};

export default function WalletSectionManager({
  paymentMethodData,
  activeTab,
  setDisablePaymentButton,
  type,
  PaybyWalletComponent,
}: WalletSectionManagerProps) {
  //
  const { user, setUser } = useUserStore();
  const { getAssetsAPI, isLoadingAsset, assets } = usePayments({
    type: type || PAYMENTS_TYPE.NORMAL,
  });
  // State to track if wallet consent is confirmed
  const [walletConsentConfirmed, setWalletConsentConfirmed] = useState(
    user?.walletConsentConfirmed,
  );

  const handleEnableConsent = useCallback(() => {
    if (user?.id) {
      setUser({
        ...user,
        walletConsentConfirmed: true,
      });
    }
    setWalletConsentConfirmed(true);
  }, [user, setUser, setWalletConsentConfirmed]);

  useEffect(() => {
    if (
      activeTab &&
      paymentMethodData &&
      paymentMethodData.id &&
      walletConsentConfirmed
    ) {
      getAssetsAPI({
        methodId: paymentMethodData.id,
      });
    }
  }, [activeTab, walletConsentConfirmed, paymentMethodData, getAssetsAPI]);

  if (isLoadingAsset) return <>Loading ...</>;

  return (
    <React.Fragment>
      {user && walletConsentConfirmed && (
        <PaybyWalletComponent
          assets={assets}
          paymentMethodData={paymentMethodData}
          setDisablePaymentButton={setDisablePaymentButton}
        />
      )}
      {user && !walletConsentConfirmed && (
        <WalletTermsAndConditionComponent
          onConsentAccepted={() => handleEnableConsent()}
        />
      )}
    </React.Fragment>
  );
}
