import React, { Suspense, lazy, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import usersService from "../../services/UsersService";
import Layout from "../Partials/Layout";
import LoadingSpinner from "../Spinners/LoadingSpinner";
const WalletBox = lazy(() => import("./WalletBox"));

const WalletRoutes = () => {
  const apiCall = new usersService();
  const { walletDetails } = useSelector((state) => state?.walletDetails); // WALLET STORE
  const { walletTable } = useSelector((state) => state.tableReload);

  const [paymentHistory, setPaymentHistory] = useState({
    loading: true,
    data: [],
  });

  const [allCountries, setAllCountries] = useState({
    // STATE TO HOLD LIST OF COUNTRIES
    loading: true,
    data: [],
  });

  const getPaymentHistory = () => {
    apiCall
      .getPaymentHx()
      .then((res) => {
        if (res.data.internal_return < 0) {
          setPaymentHistory({ loading: false, data: [] });
        } else {
          setPaymentHistory({ loading: false, data: res.data?.result_list });
        }
      })
      .catch(() => {
        setPaymentHistory({ loading: false, data: [] });
      });
  };

  // FUNCTION TO GET COUNTRIES
  const getCountry = () => {
    apiCall
      .getSignupCountryData()
      .then((res) => {
        if (res.data.internal_return < 0) {
          setAllCountries((prev) => ({ loading: false, data: [] }));
          return;
        }
        setAllCountries((prev) => ({
          loading: false,
          data: res.data.signup_country,
        }));
      })
      .catch((error) => {
        setAllCountries((prev) => ({ loading: false, data: [] }));
      });
  };

  useEffect(() => {
    getCountry();
    getPaymentHistory();
  }, [walletTable]);

  console.log(
    "Testing all country: ",
    allCountries,
    "Testing wallet: ",
    walletDetails
  );

  return (
    <Layout>
      <Suspense fallback={<LoadingSpinner size="16" color="sky-blue" />}>
        <WalletBox
          wallet={walletDetails}
          payment={paymentHistory}
          countries={allCountries.data}
        />
      </Suspense>
    </Layout>
  );
};

export default WalletRoutes;
