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 AccountBannerCom from "./AccountBannerCom";
import UpdateProfile from "./UpdateProfile";
import UpdatePassword from "./UpdatePassword";


export default function AccountEditCom() {
  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 EDIT DATA
  const account_info = accountsViewData?.account;

  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 Edit [${state?.memberUID}]`}
        paths={["Dashboard", "Account Edit"]}
      />
      
        {isFetching ? (
          <>
          <div className="box bg-white dark:bg-black-box text-black-body dark:text-white-body">
            <p className="text-slate-800">Loading...</p>
          </div>
          </>
        ) : isError ? (
          <div className="box bg-white dark:bg-black-box text-black-body dark:text-white-body">
            <p className="text-red-500">{error.message}</p>
          </div>
        ) : (
          <>
          <div className="box bg-white dark:bg-black-box text-black-body dark:text-white-body">
             <AccountBannerCom accountInfo={account_info} />
          </div>
          
          <div className="box bg-white dark:bg-black-box text-black-body dark:text-white-body">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-12 gap-5">
              <div className="p-4 col-span-12 lg:col-span-7 xl:col-span-8 shadow border rounded-xl">
                <UpdateProfile accountInfo={account_info} />
              </div>
              <div className="p-4 max-h-96 col-span-12 lg:col-span-5 xl:col-span-4 shadow border rounded-xl">
                <UpdatePassword />
              </div>
            </div>
          </div>
          </>
        )}

    </div>
  );
}
