import { useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";

import { useLocation, useNavigate } from "react-router-dom";

import BreadcrumbCom from "../breadcrumb/BreadcrumbCom";
import RouteLinks from "../../RouteLinks";
import { getAccountView } from "../../services/siteServices";
import queryKeys from "../../services/queryKeys";
import CustomerAccountView from "./CustomerAccountView";
import AccountProfileView from "./AccountProfileView";
import CustomerSubscriptionsView from "./CustomerSubscriptionsView";
import CustomerPaymentsView from "./CustomerPaymentsView";

export default function AccountViewCom() {
  const queryClient = useQueryClient();

  const { state } = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (!state?.memberUID) {
      navigate(RouteLinks.homePage, { replace: true });
    }
  }, [navigate, state?.memberUID]);

  const { data, isFetching, isError, error } = useQuery({
    queryKey: queryKeys.account_view,
    queryFn: () => {
      // const filterData = filter?.type ? {[filter?.type]: filter.id} : {}
      const reqData = {
        member_uid: state?.memberUID,
        // page,
        // ...filterData
      };
      return getAccountView(reqData);
    },
    staleTime: 0, //0 mins
  });
  const accountsViewData = data?.data; // ACCOUNT VIEW DATA
  const account_info = accountsViewData?.account;
  const account_profile = accountsViewData?.account_profile;
  const subscriptions = accountsViewData?.subscriptions;
  const payments = accountsViewData?.payments;

  useEffect(() => {
    queryClient.refetchQueries({
      queryKey: [...queryKeys.account_view],
      // type: 'active',
      // exact: true,
    });
  }, [queryClient, state?.memberUID]);

  return (
    <div className="w-full flex flex-col gap-8">
      <BreadcrumbCom
        title={`Account View [${state?.memberUID}]`}
        paths={["Dashboard", "Account View"]}
      />

      <div className="box bg-white dark:bg-black-box text-black-body dark:text-white-body">
        {isFetching ? (
          <>
            <p className="text-slate-800">Loading...</p>
          </>
        ) : isError ? (
          <p className="text-red-500">{error.message}</p>
        ) : (
          <>
            <CustomerAccountView accountInfo={account_info} />
            <AccountProfileView profile={account_profile} />
            <CustomerSubscriptionsView subscriptions={subscriptions} />
            <CustomerPaymentsView payments={payments} />
          </>
        )}
      </div>
    </div>
  );
}
