import React, {
  Suspense,
  forwardRef,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import QRCode from "react-qr-code";
import { useReactToPrint } from "react-to-print";
import usersService from "../../../services/UsersService";
import LoadingSpinner from "../../Spinners/LoadingSpinner";
import profile from "../../../assets/images/profile-info-profile.png";
import FamilyTasks from "./FamilyTasks";

export default function FamilyManageTabs({
  className,
  accountDetails,
  listReload,
  loader,
}) {
  const [details, setDetails] = useState({
    familyDetails: {
      loading: false,
      data: null,
    },
    familyTasks: {
      loading: false,
      data: null,
    },
  });
  const [errMsg, setErrMsg] = useState("");
  // List of tabs
  const tabs = [
    {
      id: 1,
      name: "Tasks",
    },
    {
      id: 2,
      name: "Account",
    },
    {
      id: 3,
      name: "Profile",
    },
  ];
  const [tab, setTab] = useState(tabs[0].name);
  const tabHandler = (value) => {
    setTab(value);
  };
  //   For profile uploads
  const [profileImg, setProfileImg] = useState(profile);
  // profile img
  const profileImgInput = useRef(null);
  const browseProfileImg = () => {
    profileImgInput.current.click();
  };
  const profileImgChangHandler = (e) => {
    if (e.target.value !== "") {
      const imgReader = new FileReader();
      imgReader.onload = (event) => {
        setProfileImg(event.target.result);
      };
      imgReader.readAsDataURL(e.target.files[0]);
    }
  };

  //   Api call
  const apiCall = useMemo(() => new usersService(), []);
  // function for manage family
  const manageFamily = useCallback(async () => {
    try {
      setDetails({
        familyDetails: { loading: true },
        familyTasks: { loading: true },
      });
      let { family_uid } = accountDetails;
      let reqData = { family_uid };

      // the family response
      const familyRes = await apiCall.ManageFamily(reqData);
      const familyData = familyRes.data;

      // the tasks response
      const tasksRes = await apiCall.ManageTasks(reqData);
      const tasksData = tasksRes.data;

      // checking the internal return
      if (familyData?.internal_return < 0 || tasksData?.internal_return < 0)
        return;

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

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

  const accountRef = useRef();
  // to handle printing
  const useHandlePrint = useReactToPrint({
    content: () => accountRef.current,
  });

  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}
                profileImgChangHandler={profileImgChangHandler}
                browseProfileImg={browseProfileImg}
                accountDetails={accountDetails}
              />
            </div>
            <div className="col-span-3 justify-self-end h-full w-full">
              <div className="flex flex-col w-full">
                <ul className="flex-[0.1] 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 ${
                        tab === name
                          ? "text-purple border-r"
                          : " text-thin-light-gray"
                      }`}
                      key={id}
                    >
                      <h1>{name}</h1>
                    </li>
                  ))}
                </ul>
                <div className="flex-[0.9] lg:min-h-[450px] h-full">
                  {/* Your content here */}
                  {tabs.map(({ name, id }) => {
                    return (
                      <div
                        className={`${
                          tab === name ? "block" : "hidden"
                        } h-full p-4 border border-[#dbd9d9] relative overflow-y-auto`}
                        key={id}
                      >
                        {name === "Tasks" && (
                          <FamilyTasks
                            className={className}
                            loader={details.familyTasks.loading}
                            familyData={details.familyTasks.data}
                          />
                        )}
                        {name === "Account" && (
                          <Account
                            familyData={details.familyDetails.data}
                            myRef={accountRef}
                            loader={details.familyDetails.loading}
                            handlePrint={useHandlePrint}
                          />
                        )}
                        {name === "Profile" && <Profile />}
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
        </Suspense>
      </div>
    </div>
  );
}

function ProfileInfo({
  profileImg,
  profileImgInput,
  profileImgChangHandler,
  browseProfileImg,
  accountDetails,
}) {
  return (
    <div className="flex flex-col items-center gap-6">
      <div className="flex justify-center">
        <div className="w-full relative">
          <img
            src={profileImg}
            alt=""
            className="sm:w-[198px] sm:h-[198px] w-[120px] h-[120px] rounded-full overflow-hidden object-cover"
          />
          <input
            ref={profileImgInput}
            onChange={(e) => profileImgChangHandler(e)}
            type="file"
            className="hidden"
          />
          <div
            onClick={browseProfileImg}
            className="w-[32px] h-[32px] absolute bottom-7 sm:right-2 right-[105px]  hover:bg-pink bg-dark-gray rounded-full cursor-pointer"
          >
            <svg
              width="32"
              height="32"
              viewBox="0 0 32 32"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M16.5147 11.5C17.7284 12.7137 18.9234 13.9087 20.1296 15.115C19.9798 15.2611 19.8187 15.4109 19.6651 15.5683C17.4699 17.7635 15.271 19.9587 13.0758 22.1539C12.9334 22.2962 12.7948 22.4386 12.6524 22.5735C12.6187 22.6034 12.5663 22.6296 12.5213 22.6296C11.3788 22.6334 10.2362 22.6297 9.09365 22.6334C9.01498 22.6334 9 22.6034 9 22.536C9 21.4009 9 20.2621 9.00375 19.1271C9.00375 19.0746 9.02997 19.0109 9.06368 18.9772C10.4123 17.6249 11.7609 16.2763 13.1095 14.9277C14.2295 13.8076 15.3459 12.6913 16.466 11.5712C16.4884 11.5487 16.4997 11.5187 16.5147 11.5Z"
                fill="white"
              />
              <path
                d="M20.9499 14.2904C19.7436 13.0842 18.5449 11.8854 17.3499 10.6904C17.5634 10.4694 17.7844 10.2446 18.0054 10.0199C18.2639 9.76139 18.5261 9.50291 18.7884 9.24443C19.118 8.91852 19.5713 8.91852 19.8972 9.24443C20.7251 10.0611 21.5492 10.8815 22.3771 11.6981C22.6993 12.0165 22.7105 12.4698 22.3996 12.792C21.9238 13.2865 21.4443 13.7772 20.9686 14.2717C20.9648 14.2792 20.9536 14.2867 20.9499 14.2904Z"
                fill="white"
              />
            </svg>
          </div>
        </div>
      </div>
      <div className="flex flex-col justify-center gap-3 items-center">
        <h1 className="font-bold text-xl tracking-wide line-clamp-1 text-dark-gray dark:text-white capitalize">
          {accountDetails?.firstname}
        </h1>
        <h1 className="font-bold text-xl tracking-wide line-clamp-1 text-dark-gray dark:text-white capitalize">
          {accountDetails?.lastname}
        </h1>
        <h1 className="font-bold text-xl tracking-wide line-clamp-1 text-dark-gray dark:text-white capitalize">
          {accountDetails?.age}
        </h1>
      </div>
    </div>
  );
}

const Account = forwardRef(({ familyData, myRef, handlePrint }, ref) => {
  return (
    <div
      className="w-full lg:min-h-[500px] h-full flex flex-col items-center justify-center"
      ref={myRef}
    >
      <div className="update-table w-full lg:min-h-[450px] h-full p-8 bg-white dark:bg-dark-white overflow-hidden rounded-2xl section-shadow ">
        <div className="flex items-center justify-around h-[380px]">
          <div className="flex flex-col">
            <h2 className="font-bold text-lg tracking-wide line-clamp-1 text-dark-gray dark:text-white capitalize">
              Username:{" "}
              <span className="ml-2 normal-case">
                {familyData?.username ? familyData?.username : "please wait..."}
              </span>
            </h2>
            <h2 className="font-bold text-lg tracking-wide line-clamp-1 text-dark-gray dark:text-white capitalize">
              Pin:{" "}
              <span className="ml-2 normal-case">
                {familyData?.pin ? familyData?.pin : "please wait..."}
              </span>
            </h2>
          </div>

          <span className="text-5xl text-gray-400 opacity-20 font-bold">
            or
          </span>

          <div className="max-w-[200px]">
            <p className="text-xl tracking-wide mb-[15px] text-center font-bold text-dark-gray dark:text-white">
              Scan the code from mobile app
            </p>
            <QRCode
              size={256}
              style={{ height: "auto", maxWidth: "100%", width: "100%" }}
              value={`https://www.google.com`}
              viewBox={`0 0 256 256`}
            />
          </div>
        </div>
        <div className="h-[50px] w-full flex justify-center items-center">
          <button
            className="btn-shine w-[116px] h-[46px] text-white rounded-full text-base bg-pink flex justify-center items-center"
            onClick={handlePrint}
          >
            Print
          </button>
        </div>
      </div>
    </div>
  );
});

function Profile() {
  return <>Profile</>;
}
