import React, {
    Suspense,
    lazy,
    useEffect,
    useMemo,
    useRef,
    useState,
  } from "react";
  import usersService from "../../services/UsersService";
  import LoadingSpinner from "../Spinners/LoadingSpinner";
  import AssignTaskPopout from "./FamilyPopout/AssignTaskPopout";
  import { apiConst } from "../../lib/apiConst";
  
  // Lazy Imports for components
  const FamilyWaitlist = lazy(() => import("./Tabs/FamilyNewWaitlist"));
  const FamilyTasks = lazy(() => import("./Tabs/FamilyTasks"));
  const FamilyPending = lazy(() => import("./Tabs/FamilyPending"));
  
  export default function FamilyTableNew({
    className,
    accountDetails,
    listReload,
    loader,
  }) {
    // Initial state for family details
    const initialDetailState = {
      loading: false,
      data: null,
    };
  // console.log('accountDetails',accountDetails)
    // State for family details, tasks, waitlist, and pending
    const [details, setDetails] = useState({
      familyDetails: { ...initialDetailState },
      familyTasks: { ...initialDetailState },
      familyWaitList: { ...initialDetailState },
      familyPending: { ...initialDetailState },
    });
  
    // Function to reset family details, tasks, waitlist, and pending
    const resetDetails = () => {
      setDetails({
        familyDetails: { ...initialDetailState },
        familyTasks: { ...initialDetailState },
        familyWaitList: { ...initialDetailState },
        familyPending: { ...initialDetailState },
      });
    };
  
    const [updatePage, setUpdatePage] = useState(false) // State to determine when to update the page
  
    // State for family task data
    const [familyTask, setFamilyTask] = useState({ loading: false, data: [] });
  
    // State for active task
    const [activeTask, setActiveTask] = useState({ id: 0, data: {} });
  
    // State for error messages
    const [errMsg, setErrMsg] = useState("");
  
    // State for family task popout
    const [familyTaskPopout, setFamilyTaskPopout] = useState(false);
  
    // Create an instance of the usersService class
    const apiCall = useMemo(() => new usersService(), []);
  
    // Function to handle toggling the family task popout
    const familyPopUpHandler = () => {
      setFamilyTaskPopout((prev) => !prev);
    };
  
    // Array of tab names
    const tabs = [
      { id: 1, name: "Tasks" },
      { id: 2, name: "Waiting" },
      { id: 3, name: "Pending" },
    ];
  
    // State for the currently selected tab
    const [tab, setTab] = useState(tabs[0].name);
  
    // Function to handle tab changes
    const tabHandler = (value) => {
      setTab(value);
    };
  
    // Object that maps tab names to their corresponding components
    const tabComponents = {
      Tasks: (
        // <FamilyTasks
        //   className={className}
        //   loader={details.familyTasks.loading || false}
        //   familyData={details.familyTasks.data || {}}
        //   accountDetails={accountDetails || {}}
        // />
        <FamilyWaitlist
          familyData={details.familyWaitList.data}
          accountDetails={accountDetails}
          loader={details.familyWaitList.loading}
        />
      ),
      Waiting: (
        <FamilyWaitlist
          familyData={details.familyWaitList.data}
          accountDetails={accountDetails}
          loader={details.familyWaitList.loading}
        />
      ),
      Pending: (
        <FamilyPending
          familyData={details.familyPending.data}
          accountDetails={accountDetails}
          loader={details.familyPending.loading}
        />
      ),
    };

    const defaultTabComponent = tabComponents.Tasks;
  
    // Selected tab component based on the current 'tab'
    const selectedTabComponent = tabComponents[tab] || defaultTabComponent;
  
    // Effect to manage family details and related data
    useEffect(() => {
      const manageFamily = async () => {
        try {
          resetDetails();
  
          setDetails({
            familyDetails: { loading: true },
            familyTasks: { loading: true },
            familyWaitList: { loading: true },
            familyPending: { loading: true },
          });
  
        //   const { family_uid } = accountDetails;
        //   const reqData = { family_uid };
  
          const [familyWaitRes, familyPending] =
            await Promise.all([
            //   apiCall.ManageFamily(reqData),
            //   apiCall.ManageTasks(reqData),
              apiCall.ManageFamilyNewWaitlist(),
              apiCall.ManageFamilyPending(),
            ]);
  
        //   const familyData = familyRes.data;
        //   const tasksData = tasksRes.data;
          const familyWaitData = familyWaitRes.data;
          const familyPendingData = familyPending.data;
  
          // Function to check for errors in data
          const checkDataError = (data) => data?.internal_return < 0;
  
          if (
            // checkDataError(familyData) ||
            // checkDataError(tasksData) ||
            checkDataError(familyWaitData) ||
            checkDataError(familyPendingData)
          ) {
            return;
          }
  
          setDetails({
            // familyDetails: { loading: false, data: familyData },
            // familyTasks: { loading: false, data: tasksData },
            familyWaitList: { loading: false, data: familyWaitData },
            familyPending: { loading: false, data: familyPendingData },
          });
        } catch (error) {
          resetDetails();
          setErrMsg("An error occurred");
          throw new Error(error);
        }
      };
  
      // Invoke the manageFamily function when the component mounts
      manageFamily();
    }, [updatePage]);
  
    // Effect to manage family tasks
    useEffect(() => {
      let checkFamilyTask = true;
      const reqData = {
        limit: 30,
        offset: 0,
        job_type: "FAMILY",
        action: apiConst.WRENCHBOARD_PICTURE_FAMMEMBER,
      };
  
      if (checkFamilyTask) {
        setFamilyTask({ loading: true });
        apiCall
          .getMyJobList(reqData)
          .then((res) => {
            setFamilyTask({ loading: false, data: res?.data?.result_list });
            if (res?.data?.result_list?.length) {
              setActiveTask((prev) => ({
                ...prev,
                data: res?.data?.result_list[0],
              }));
            }
          })
          .catch((err) => {
            setFamilyTask({ loading: false, data: [] });
            console.log("Error", err);
          });
      }
  
      // Cleanup function to prevent memory leaks
      return () => {
        checkFamilyTask = false;
      };
    }, []);

    console.log("God please>> ", details.familyWaitList)
  
    return (
      <div
        className={`w-full bg-white dark:bg-dark-white overflow-y-auto rounded-2xl section-shadow h-full ${
          className || ""
        }`}
      >
        <div className="relative w-full sm:rounded-lg overflow-x-auto">
          <Suspense
            fallback={
              <div className="h-full min-h-[609px] w-full overflow-hidden flex justify-center items-center">
                <LoadingSpinner size="16" color="sky-blue" />
              </div>
            }
          >
            <div className="w-full h-full text-sm text-left text-gray-500 dark:text-gray-400 relative grid grid-cols-3 min-h-[575px]">
              <div className="col-span-3 h-full w-full">
                <div className="flex flex-col w-full">
                  <div className="w-full pr-8 flex items-center gap-1 border-b border-b-[#FAFAF]">
                    <ul className="flex gap-2 items-center w-full">
                      {tabs.map(({ name, id }) => (
                        <li
                          onClick={() => tabHandler(name)}
                          className={`p-4 flex hover:text-purple transition-all ease-in-out items-center cursor-pointer overflow-hidden text-xl relative top-[2px] ${
                            tab === name
                              ? "text-purple border-r"
                              : "text-thin-light-gray"
                          }`}
                          key={id}
                        >
                          <h1>{name}</h1>
                        </li>
                      ))}
                    </ul>
                    <button
                      type="button"
                      onClick={familyPopUpHandler}
                      className="p-1 my-1 w-[100px] flex justify-center items-center btn-gradient text-base rounded-full text-white"
                    >
                      Add task
                    </button>
                  </div>
  
                  <div className="flex-[0.9] h-full">
                    <div className="h-full relative overflow-y-auto">
                      <Suspense
                        fallback={<LoadingSpinner size="16" color="sky-blue" />}
                      >
                        {selectedTabComponent}
                      </Suspense>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Suspense>
        </div>
  
        {familyTaskPopout && (
          <AssignTaskPopout
            action={familyPopUpHandler}
            situation={familyTaskPopout}
            familyTask={familyTask}
            setFamilyTask={setFamilyTask}
            setActiveTask={setActiveTask}
            activeTask={activeTask}
            familyDetailsData={details.familyDetails.data}
            setUpdatePage={setUpdatePage}
          />
        )}
      </div>
    );
  }
  