import React, {
  Suspense,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useReactToPrint } from "react-to-print";
import profile from "../../assets/images/profile-info-profile.png";
import usersService from "../../services/UsersService";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import AssignTaskPopout from "./FamilyPopout/AssignTaskPopout";
import {
  FamilyWaitlist,
  FamilyAccount,
  FamilyProfile,
  FamilyTasks,
  ProfileInfo,
  FamilyPending,
} from "./Tabs";

export default function FamilyManageTabs({
  className,
  accountDetails,
  listReload,
  loader,
}) {
  const [details, setDetails] = useState({
    familyDetails: { loading: false, data: null },
    familyTasks: { loading: false, data: null },
    familyWaitList: { loading: false, data: null },
    familyPending: { loading: false, data: null },
  });
  const [errMsg, setErrMsg] = useState("");
  const [familyTaskPopout, setFamilyTaskPopout] = useState(false);

  const familyPopUpHandler = () => {
    setFamilyTaskPopout((prev) => !prev);
  };

  const [profileImg, setProfileImg] = useState(profile);
  const profileImgInput = useRef(null);

  const browseProfileImg = () => {
    profileImgInput.current.click();
  };

  const profileImgChangeHandler = (e) => {
    if (e.target.value !== "") {
      const imgReader = new FileReader();
      imgReader.onload = (event) => {
        setProfileImg(event.target.result);
      };
      imgReader.readAsDataURL(e.target.files[0]);
    }
  };

  const apiCall = useMemo(() => new usersService(), []);

  const manageFamily = useCallback(async () => {
    try {
      setDetails({
        familyDetails: { loading: true },
        familyTasks: { loading: true },
        familyWaitList: { loading: true },
        familyPending: { loading: true },
      });

      const { family_uid } = accountDetails;
      const reqData = { family_uid };

      const [familyRes, tasksRes, familyWaitRes, familyPending] =
        await Promise.all([
          apiCall.ManageFamily(reqData),
          apiCall.ManageTasks(reqData),
          apiCall.ManageFamilyWaitlist(),
          apiCall.ManageFamilyPending(),
        ]);

      const familyData = familyRes.data;
      const tasksData = tasksRes.data;
      const familyWaitData = familyWaitRes.data;
      const familyPendingData = familyPending.data;

      if (
        familyData?.internal_return < 0 ||
        tasksData?.internal_return < 0 ||
        familyWaitData?.internal_return < 0 ||
        familyPendingData?.internal_return < 0
      )
        return;

      setDetails({
        familyDetails: { loading: false, data: familyData },
        familyTasks: { loading: false, data: tasksData },
        familyWaitList: { loading: false, data: familyWaitData },
        familyPending: { loading: false, data: familyPendingData },
      });
    } catch (error) {
      setDetails({
        familyDetails: { loading: false },
        familyTasks: { loading: false },
        familyWaitList: { loading: false },
        familyPending: { loading: false },
      });
      setErrMsg("An error occurred");
      throw new Error(error);
    }
  }, [apiCall, accountDetails]);

  const accountRef = useRef();

  const useHandlePrint = useReactToPrint({
    content: () => accountRef.current,
  });

  const tabs = [
    { id: 1, name: "Tasks" },
    { id: 2, name: "Waiting" },
    { id: 3, name: "Pending" },
    { id: 4, name: "Account" },
    { id: 5, name: "Profile" },
  ];

  const [tab, setTab] = useState(tabs[0].name);

  const tabHandler = (value) => {
    setTab(value);
  };

  const tabComponents = {
    Tasks: (
      <FamilyTasks
        className={className}
        loader={details.familyTasks.loading}
        familyData={details.familyTasks.data}
        accountDetails={accountDetails}
      />
    ),
    Waiting: (
      <FamilyWaitlist
        familyData={details.familyWaitList.data}
        accountDetails={accountDetails}
        loader={details.familyWaitList.loading}
      />
    ),
    Pending: (
      <FamilyPending
        familyData={details.familyPending.data}
        accountDetails={accountDetails}
        loader={details.familyWaitList.loading}
      />
    ),
    Account: (
      <FamilyAccount
        familyData={details.familyDetails.data}
        myRef={accountRef}
        loader={details.familyDetails.loading}
        handlePrint={useHandlePrint}
      />
    ),
    Profile: <FamilyProfile />,
  };

  const defaultTabComponent = (
    <FamilyTasks
      className={className}
      loader={details.familyTasks.loading}
      familyData={details.familyTasks.data}
      accountDetails={accountDetails}
    />
  );

  const selectedTabComponent = tabComponents[tab] || defaultTabComponent;

  useEffect(() => {
    manageFamily();
  }, [tab, manageFamily]);

  return (
    <div
      className={`w-full bg-white dark:bg-dark-white overflow-y-auto rounded-2xl section-shadow min-h-[520px] max-h-[600px] ${
        className || ""
      }`}
    >
      <div className="relative w-full overflow-x-auto sm:rounded-lg">
        <Suspense
          fallback={
            <div className="h-full min-h-[500px] 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-4 min-h-[520px]">
            <div className="border-r border-[#E3E4FE] dark:border-[#a7a9b533] p-6 h-full">
              <ProfileInfo
                profileImg={profileImg}
                profileImgInput={profileImgInput}
                profileImgChangeHandler={profileImgChangeHandler}
                browseProfileImg={browseProfileImg}
                accountDetails={accountDetails}
              />
            </div>
            <div className="col-span-3 justify-self-end h-full w-full">
              <div className="flex flex-col w-full">
                <div className="w-full pr-8 flex items-center gap-1">
                  <ul className="flex gap-2 items-center border-b border-b-[#FAFAF] 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] lg:min-h-[450px] h-full">
                  <div className="h-full p-4 border border-[#dbd9d9] relative overflow-y-auto">
                    {selectedTabComponent}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Suspense>
      </div>

      {familyTaskPopout && (
        <AssignTaskPopout
          action={familyPopUpHandler}
          situation={familyTaskPopout}
          familyDetails={details.familyDetails.data}
        />
      )}
    </div>
  );
}
