"use client";

import "../../style/globals.css";
import { Inter } from "next/font/google";
import "../../style/fontiran.css";
import NavBAr from "@comp/NavBar/NavBAr";
import "swiper/css";
import "swiper/css/navigation";
import "react-spring-bottom-sheet/dist/style.css";
import AppContext from "../../Contexts/AppContext";
import { useCallback, useEffect, useState } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Loading from "plugins/Loading/page";
import Chapar, { getToken } from "plugins/Chapar";
import TimePicker from "plugins/TimePicker/page";
import axios from "axios";
import "rc-slider/assets/index.css";
import BottomSheetReport from "plugins/BottomSheet/BottomSheetReport";
import BottomSheetReportManageShift from "plugins/BottomSheet/BottomSheetReportManageShift";

const inter = Inter({ subsets: ["latin"] });

// export const metadata = {
//   title: "Create Next App",
//   description: "Generated by create next app",
// };

export default function RootLayout({ children }) {
  // BottomSheet
  const [BottomSheetCreateRoleOpen, setBottomSheetCreateRoleOpen] =
    useState(false);

  const [BottomSheetCreateEmployeesOpen, setBottomSheetCreateEmployeesOpen] =
    useState(false);

  const [BottomSheetCreateShiftsOpen, setBottomSheetCreateShiftsOpen] =
    useState(false);

  const [BottomManageShiftOpen, setBottomManageShiftOpen] = useState(false);
  const [BottomFilterActivitiesOpen, setBottomFilterActivitiesOpen] =
    useState(false);
  const [BottomSheetCreateRoutineOpen, setBottomSheetCreateRoutineOpen] =
    useState(false);
  const [BottomSheetCreateSectionOpen, setBottomSheetCreateSectionOpen] =
    useState(false);

  const [BottomSheetCreatePositionOpen, setBottomSheetCreatePositionOpen] =
    useState(false);

  const [
    BottomSheetAddUserToPositionShiftPlanOpen,
    setBottomSheetAddUserToPositionShiftPlanOpen,
  ] = useState(false);

  const [BottomSheetChangeRoleOpen, setBottomSheetChangeRoleOpen] =
    useState(false);

  const [BottomSheetReportOpen, setBottomSheetReportOpen] = useState(false);
  const [
    BottomSheetReportManageShiftOpen,
    setBottomSheetReportManageShiftOpen,
  ] = useState(false);

  // BigPlus
  const [BigPlusOpen, setBigPlusOpen] = useState(false);
  const [BigPlusRotateIcon, setBigPlusRotateIcon] = useState(false);

  // login
  const [phoneNumber, setPhoneNumber] = useState("");
  const [verifyCode, setVerifyCode] = useState("");
  const [stepLogin, setStepLogin] = useState(0);
  const [tokenForStorage, setTokenForStorage] = useState(null);
  const [profile, setProfile] = useState([]);

  // loading

  const [loading, setLoading] = useState(false);

  //auth
  const [complexId, setComplexId] = useState(0);

  // createRole / role
  const [permissions, setPermissions] = useState(0);
  const [permissionsChoose, setPermissionsChoose] = useState([]);
  const [rolesData, setRolesData] = useState([]);
  const [roleData, setRoleData] = useState([]);
  const [goToEditRole, setGoToEditRole] = useState(false);
  const [idEditRole, setIdEditRole] = useState(null);

  // createUser/ user
  const [usersData, setUsersData] = useState([]);
  const [rolesChoose, setRolesChoose] = useState([]);
  const [userData, setUserData] = useState([]);
  const [goToEditUser, setGoToEditUser] = useState(false);
  const [idEditUser, setIdEditUser] = useState(null);

  // createsection/ section
  const [sectionsData, setSectionsData] = useState([]);
  const [sectionData, setSectionData] = useState([]);
  const [goToEditSection, setGoToEditSection] = useState(false);
  const [idEditSection, setIdEditSection] = useState(null);

  // createroutine/ routine
  const [routinesData, setRoutinesData] = useState([]);
  const [routineData, setRoutineData] = useState([]);
  const [routineShiftPlan, setRoutineShiftPlan] = useState([]);
  const [goToEditRoutine, setGoToEditRoutine] = useState(false);
  const [idEditRoutine, setIdEditRoutine] = useState(null);

  // createPosition/ Position
  const [positionsData, setPositionsData] = useState([]);
  const [positionData, setPositionData] = useState([]);
  const [goToEditPosition, setGoToEditPosition] = useState(false);
  const [idEditPosition, setIdEditPosition] = useState(null);
  const [sectionIdChoose, setSectionIdChoose] = useState([]);

  // shift
  const [dayOfWeeksChoose, setDayOfWeeksChoose] = useState([]);
  const [startAtTimeShift, setStartAtTimeShift] = useState(["00", "00"]);
  const [endAtTimeShift, setEndAtTimeShift] = useState(["00", "00"]);
  const [shiftsData, setShiftsData] = useState([null]);
  const [shiftData, setShiftData] = useState([null]);
  const [goToEditShift, setGoToEditShift] = useState(false);
  const [idEditShift, setIdEditShift] = useState(null);
  const [shiftPlanData, setShiftPlanData] = useState([]);
  const [shiftPlansData, setShifPlansData] = useState([]);

  // task
  const [routineForTaskChoose, setRoutineForTaskChoose] = useState([]);
  const [positionsForTaskChoose, setPositionsForTaskChoose] = useState([]);
  const [shiftsForTaskChoose, setShiftsForTaskChoose] = useState([]);
  const [shiftsDaysChoose, setShiftsDaysChoose] = useState([]);
  const [tasksData, setTasksData] = useState([]);
  const [taskData, setTaskData] = useState([]);
  const [goToEditTask, setGoToEditTask] = useState(false);
  const [idEditTask, setIdEditTask] = useState(null);
  const [pageGetTasks, setPageGetTasks] = useState(0);
  const [stopGetTasks, setStopGetTasks] = useState(false);
  const [typeTask, setTypeTask] = useState(1);

  // activity
  const [activitiesData, setActivitiesData] = useState([]);
  const [pageGetActivity, setPageGetActivity] = useState(0);
  const [stopGetActivities, setStopGetActivities] = useState(false);

  // shift manage-shift
  const [searchUserChoose, setSearchUserChoose] = useState([]);

  // TimePicker
  const [openTimePicker, setOpenTimePicker] = useState(false);
  const [TimePickerOrder, setTimePickerOrder] = useState(null);

  // closeShift
  const [completeActivities, setCompleteActivities] = useState([]);

  //report
  const [reportDetail, setReportDetail] = useState(null);

  //home page
  const [homePageData, setHomePageData] = useState([]);

  const pathname = usePathname();
  const router = useRouter();
  const hiddenUrls = ["/login", "/pricing", "/about-us", "/"];
  const shouldRenderComponent = !hiddenUrls.includes(pathname);

  const closeBigPlusPage = () => {
    setTimeout(() => {
      setBigPlusOpen(false);
    }, 500);

    setBigPlusRotateIcon(false);
  };
  const ConfirmPhoneNumber = async (phoneNumber) => {
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/verifycode?phoneNumber=${phoneNumber}`
      );
      setStepLogin(1);
      localStorage.removeItem("token");
    } catch ({ error, status }) {
      toast.error("  اطلاعات را صحیح وارد کنید ", {
        position: "bottom-right",
        closeOnClick: true,
      });
    }
  };
  const LoginWhitVerifyCode = async () => {
    setLoading(true);

    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/login/code`,
        {
          userName: phoneNumber,
          password: null,
          verifyCode,
        }
      );
      setLoading(false);
      localStorage.setItem("token", data.access_token);

      if (data.user.signUpStatus == 1) {
        setStepLogin(2);
      } else if (data.user.signUpStatus == 2 || data.user.signUpStatus == 3) {
        setProfile(data);
        toast.success(`${data.user.firstName} جان خوش اومدی `, {
          position: "bottom-right",
          closeOnClick: true,
        });
        router.push("/home");
      }
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const SignUpLogin = async (body) => {
    setLoading(true);

    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/signup/complex`,
        body,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setLoading(false);

      if (data.user.signUpStatus == 2 || data.user.signUpStatus == 3) {
        setProfile(data);

        toast.success(`  ${data.user.firstName}  جان خوش اومدی `, {
          position: "bottom-right",
          closeOnClick: true,
        });
        // localStorage.removeItem("token");
        localStorage.setItem("token", data.access_token);

        router.push("/home");
      }
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetPermissions = async (body) => {
    setLoading(true);

    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/role/permission`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setPermissions(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateRole = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/role`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`نقش ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateRoleOpen(false);
      setLoading(false);
      GetRoles();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateRole = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/role`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`نقش ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateRoleOpen(false);
      setLoading(false);
      GetRoles();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetRoles = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/role?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setRolesData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetRole = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/role/${id}?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setRoleData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteRole = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/role/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreateRoleOpen(false);
      setLoading(false);

      GetRoles();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateUser = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/user`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`کاربر ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateEmployeesOpen(false);
      setLoading(false);
      GetUsers();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateUser = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/user`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`کاربر ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateEmployeesOpen(false);
      setLoading(false);
      GetUsers();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetUsers = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/user?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setUsersData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetUser = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/user/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setUserData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteUser = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/user/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreateEmployeesOpen(false);
      setLoading(false);

      GetUsers();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateShift = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/shift`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`شیفت ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateShiftsOpen(false);
      setLoading(false);
      GetShifts();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateShift = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/shift`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`شیفت ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      setBottomSheetCreateShiftsOpen(false);
      setLoading(false);
      GetShifts();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetShifts = async (date) => {
    console.log(
      "Date123456789",
      `${process.env.NEXT_PUBLIC_API_URL}/shift?page=0${
        date ? `&selectedDate=${date}` : ""
      }`
    );
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/shift?page=0${
          date ? `&selectedDate=${date}` : ""
        }`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setShiftsData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetShift = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setShiftData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteShift = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreateShiftsOpen(false);

      setLoading(false);
      GetShifts();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateSection = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/section`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`سکشن ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateSectionOpen(false);
      setLoading(false);
      GetSections();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateSection = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/section`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`سکشن ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      setBottomSheetCreateSectionOpen(false);
      setLoading(false);
      GetSections();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetSections = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/section?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setSectionsData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetSection = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/section/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setSectionData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteSection = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/section/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreateSectionOpen(false);

      setLoading(false);
      GetSections();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateRoutine = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/routine`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`روتین ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreateRoutineOpen(false);
      setLoading(false);
      GetRoutines();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateRoutine = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/routine`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`روتین ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      setBottomSheetCreateRoutineOpen(false);
      setLoading(false);
      GetRoutines();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetRoutines = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/routine?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setRoutinesData(data);
      setLoading(false);
    } catch (error) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
      // if (error.response.status === 401) {
      //   localStorage.removeItem("token");
      // window.location.href = "/";
      // }
    }
  };
  const GetRoutine = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/routine/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setRoutineData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetRoutineShiftPlan = async (id, time) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/routine/${id}/shift?selectedDate=${time}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setRoutineShiftPlan(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetShiftPlan = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/plan/${id}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setShiftPlanData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  // const UpdateShiftPlan = async (body, id) => {
  //   setLoading(true);
  //   try {
  //     const data = await Chapar.put(
  //       `${process.env.NEXT_PUBLIC_API_URL}/shift/plan`,
  //       body,

  //       {
  //         headers: {
  //           Authorization: "Bearer " + localStorage.getItem("token"),
  //         },
  //       }
  //     );
  //     toast.success(`شیفت ویرایش شد`, {
  //       position: "bottom-right",
  //       closeOnClick: true,
  //     });

  //     setLoading(false);
  //     setShiftPlanData(id);
  //     router.push("/shifts");
  //   } catch ({ error, status }) {
  //     toast.error(`${error?.response?.data?.message}`, {
  //       position: "bottom-right",
  //       closeOnClick: true,
  //     });
  //     setLoading(false);
  //   }
  // };
  // const CreateShifPlan = async (body) => {
  //   setLoading(true);
  //   try {
  //     const data = await Chapar.post(
  //       `${process.env.NEXT_PUBLIC_API_URL}/shift/plan`,
  //       JSON.stringify(body),
  //       {
  //         headers: {
  //           Authorization: "Bearer " + localStorage.getItem("token"),
  //         },
  //       }
  //     );
  //     toast.success(`مدیریت شیفت ساخته شد`, {
  //       position: "bottom-right",
  //       closeOnClick: true,
  //     });

  //     router.push("/shifts");

  //   } catch ({ error, status }) {
  //     toast.error(`${error?.response?.data?.message}`, {
  //       position: "bottom-right",
  //       closeOnClick: true,
  //     });
  //     setLoading(false);
  //   }
  // };
  const GetShifPlans = async (page, dataFilter) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/plan?page=${page}&dateFilter=${dataFilter}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      console.log(data);

      setShifPlansData(data);

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteRoutine = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/routine/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreateRoutineOpen(false);

      setLoading(false);
      GetRoutines();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreatePosition = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/position`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`پوزیشن ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setBottomSheetCreatePositionOpen(false);
      setLoading(false);
      GetPositions();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdatePosition = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/position`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`پوزیشن ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      setBottomSheetCreatePositionOpen(false);
      setLoading(false);
      GetPositions();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetPositions = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/position?page=0`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setPositionsData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetPosition = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/position/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setPositionData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeletePosition = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/position/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setBottomSheetCreatePositionOpen(false);

      setLoading(false);
      GetPositions();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const CreateTask = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/task`,
        JSON.stringify(body),
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ساخته شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      // router->

      setLoading(false);
      GetTasks(0);

      router.push("/tasks");
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UpdateTask = async (body) => {
    setLoading(true);
    try {
      const data = await Chapar.put(
        `${process.env.NEXT_PUBLIC_API_URL}/task`,
        body,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ویرایش شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });

      // router->

      setLoading(false);
      GetTasks(0);
      router.push("/tasks");
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetTasks = async (page) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/task?page=${page}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      if (data.length < 14) {
        setStopGetTasks(true);
      }
      if (page == 0) {
        setTasksData(data);
      } else {
        setTasksData((prevData) => [...prevData, ...data]);
      }

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const GetTask = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/task/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setTaskData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DeleteTask = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.delete(
        `${process.env.NEXT_PUBLIC_API_URL}/task/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      setLoading(false);
      GetTasks();
      router.push("/tasks");
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const GetActivity = async (date, shift, page, dateQueryFilter) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/activity?page=${page}${
          date ? `&selectedDate=${date}` : ""
        }${shift ? `&selectedShift=${shift}` : ""}${
          dateQueryFilter != null ? `&dateQueryFilter=${dateQueryFilter}` : ""
        }`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      if (data.length < 19) {
        setStopGetActivities(true);
      }

      if (page == 0) {
        setActivitiesData(data);
      } else {
        setActivitiesData((prevData) => [...prevData, ...data]);
      }

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const DoneActivity = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/activity/done/${id}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ثبت شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      // router->

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };
  const UnDoneActivity = async (id, resone) => {
    setLoading(true);

    console.log("s");
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/activity/undone/${id}?undoneReason=${resone}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ثبت شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      // router->

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const CloseShift = async (body, id, index) => {
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/shift/plan/${id}/complete`,
        body,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      toast.success(`فعالیت ثبت شد`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      // router->

      CTX.GetShifts(moment().locale("fa").startOf("day").unix() * 1000);

      setLoading(false);
      // GetTasks();
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const changeRole = async (id) => {
    console.log(getToken());
    setLoading(true);
    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/user/role/change/${id}`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setProfile(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const CheckUser = async () => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/user/profile`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );
      setProfile(data);

      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const ReportShiftPlan = async (shiftPlanId) => {
    setLoading(true);
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/report/shift/plan/${shiftPlanId}`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      if (!response.ok) {
        throw new Error("Failed to download report");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "report.xlsx"; // Change the filename if needed
      document.body.appendChild(a);
      a.click();
      a.remove();

      setLoading(false);
    } catch (error) {
      toast.error(error.message, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const ReportTask = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/report/task`,
        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      if (!response.ok) {
        throw new Error("Failed to download report");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "report.xlsx"; // Change the filename if needed
      document.body.appendChild(a);
      a.click();
      a.remove();

      setLoading(false);
    } catch (error) {
      toast.error(error.message, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  const GetHomePageData = async (id) => {
    setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/page/dashboard/app`,

        {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }
      );

      console.log(data);
      setHomePageData(data);
      setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log(`
    bbbbbbbb                                                                                        
    b::::::b                               iiii                                                     
    b::::::b                              i::::i                                                    
    b::::::b                               iiii                                                     
     b:::::b                                                                                        
     b:::::bbbbbbbbb   rrrrr   rrrrrrrrr iiiiiiizzzzzzzzzzzzzzzzz   cccccccccccccccc  ooooooooooo   
     b::::::::::::::bb r::::rrr:::::::::ri:::::iz:::::::::::::::z cc:::::::::::::::coo:::::::::::oo 
     b::::::::::::::::br:::::::::::::::::ri::::iz::::::::::::::z c:::::::::::::::::o:::::::::::::::o
     b:::::bbbbb:::::::rr::::::rrrrr::::::i::::izzzzzzzz::::::z c:::::::cccccc:::::o:::::ooooo:::::o
     b:::::b    b::::::br:::::r     r:::::i::::i      z::::::z  c::::::c     cccccco::::o     o::::o
     b:::::b     b:::::br:::::r     rrrrrri::::i     z::::::z   c:::::c            o::::o     o::::o
     b:::::b     b:::::br:::::r           i::::i    z::::::z    c:::::c            o::::o     o::::o
     b:::::b     b:::::br:::::r           i::::i   z::::::z     c::::::c     cccccco::::o     o::::o
     b:::::bbbbbb::::::br:::::r          i::::::i z::::::zzzzzzzc:::::::cccccc:::::o:::::ooooo:::::o
     b::::::::::::::::b r:::::r          i::::::iz::::::::::::::zc:::::::::::::::::o:::::::::::::::o
     b:::::::::::::::b  r:::::r          i::::::z:::::::::::::::z cc:::::::::::::::coo:::::::::::oo 
     bbbbbbbbbbbbbbbb   rrrrrrr          iiiiiiizzzzzzzzzzzzzzzzz   cccccccccccccccc  ooooooooooo   

     soli chizi bood bgo hossein__masoomi                                                                                   
                                                                                                
    `);
    const token = localStorage.getItem("token");
    // if (!token) {
    //   router.push("/login");
    // }

    if (profile.length <= 0 && token) CheckUser();
  }, []);

  return (
    <AppContext.Provider
      value={{
        state: {
          BottomSheetCreateRoleOpen,
          BottomSheetCreateEmployeesOpen,
          BottomSheetCreateShiftsOpen,
          BigPlusOpen,
          BigPlusRotateIcon,
          loading,
          stepLogin,
          phoneNumber,
          verifyCode,
          tokenForStorage,
          complexId,
          permissions,
          permissionsChoose,
          rolesData,
          usersData,
          rolesChoose,
          goToEditRole,
          roleData,
          idEditRole,
          idEditUser,
          goToEditUser,
          userData,
          openTimePicker,
          endAtTimeShift,
          startAtTimeShift,
          TimePickerOrder,
          shiftsData,
          idEditShift,
          goToEditShift,
          shiftData,
          profile,
          searchUserChoose,
          BottomManageShiftOpen,
          idEditSection,
          goToEditSection,
          sectionData,
          sectionsData,
          BottomSheetCreateSectionOpen,
          BottomSheetCreateRoutineOpen,
          idEditRoutine,
          goToEditRoutine,
          routineData,
          routinesData,
          dayOfWeeksChoose,
          idEditPosition,
          goToEditPosition,
          positionData,
          positionsData,
          BottomSheetCreatePositionOpen,
          sectionIdChoose,
          routineForTaskChoose,
          positionsForTaskChoose,
          shiftsForTaskChoose,
          shiftsDaysChoose,
          idEditTask,
          goToEditTask,
          taskData,
          tasksData,
          routineShiftPlan,
          BottomSheetAddUserToPositionShiftPlanOpen,
          BottomSheetChangeRoleOpen,
          activitiesData,
          completeActivities,
          shiftPlanData,
          stopGetTasks,
          pageGetTasks,
          stopGetActivities,
          pageGetActivity,
          shiftPlansData,
          BottomSheetReportOpen,
          reportDetail,
          BottomFilterActivitiesOpen,
          homePageData,
          typeTask,
          BottomSheetReportManageShiftOpen,
        },
        setBottomSheetCreateRoleOpen,
        setBottomSheetCreateEmployeesOpen,
        setBottomSheetCreateShiftsOpen,
        setBigPlusOpen,
        setBigPlusRotateIcon,
        setLoading,
        ConfirmPhoneNumber,
        LoginWhitVerifyCode,
        setStepLogin,
        setPhoneNumber,
        setVerifyCode,
        SignUpLogin,
        setTokenForStorage,
        setComplexId,
        setPermissions,
        GetPermissions,
        setPermissionsChoose,
        CreateRole,
        setRolesData,
        GetRoles,
        CreateUser,
        GetUsers,
        setUsersData,
        setRolesChoose,
        setGoToEditRole,
        setRoleData,
        GetRole,
        setIdEditRole,
        DeleteRole,
        UpdateRole,
        setIdEditUser,
        setGoToEditUser,
        setUserData,
        DeleteUser,
        GetUser,
        UpdateUser,
        setOpenTimePicker,
        setEndAtTimeShift,
        setIdEditShift,
        setGoToEditShift,
        setStartAtTimeShift,
        setBottomManageShiftOpen,
        GetShifts,
        DeleteShift,
        GetShift,
        UpdateShift,
        CreateShift,
        setIdEditSection,
        setGoToEditSection,
        setSectionData,
        setSectionsData,
        setBottomSheetCreateSectionOpen,
        DeleteSection,
        GetSection,
        GetSections,
        UpdateSection,
        CreateSection,
        setBottomSheetCreateRoutineOpen,
        setIdEditRoutine,
        setGoToEditRoutine,
        setRoutineData,
        setRoutinesData,
        DeleteRoutine,
        GetRoutine,
        GetRoutines,
        UpdateRoutine,
        CreateRoutine,
        setDayOfWeeksChoose,
        setShiftData,
        setTimePickerOrder,
        setSearchUserChoose,
        setIdEditPosition,
        setGoToEditPosition,
        setPositionData,
        setPositionsData,
        setBottomSheetCreatePositionOpen,
        DeletePosition,
        GetPosition,
        GetPositions,
        UpdatePosition,
        CreatePosition,
        setSectionIdChoose,
        setRoutineForTaskChoose,
        setPositionsForTaskChoose,
        setShiftsForTaskChoose,
        setShiftsDaysChoose,
        DeleteTask,
        GetTask,
        GetTasks,
        UpdateTask,
        CreateTask,
        setIdEditTask,
        setGoToEditTask,
        setTaskData,
        setTasksData,
        setRoutineShiftPlan,
        GetRoutineShiftPlan,
        setBottomSheetAddUserToPositionShiftPlanOpen,
        // CreateShifPlan,
        setBottomSheetChangeRoleOpen,
        setActivitiesData,
        GetActivity,
        UnDoneActivity,
        DoneActivity,
        changeRole,
        setCompleteActivities,
        CloseShift,
        setShiftPlanData,
        GetShiftPlan,
        // UpdateShiftPlan,
        setStopGetTasks,
        setPageGetTasks,
        setStopGetActivities,
        setPageGetActivity,
        setShifPlansData,
        GetShifPlans,
        setBottomSheetReportOpen,
        setReportDetail,
        ReportShiftPlan,
        ReportTask,
        setBottomFilterActivitiesOpen,
        setHomePageData,
        GetHomePageData,
        setTypeTask,
        setBottomSheetReportManageShiftOpen,
      }}
    >
      <html lang="en">
        <body className={inter.className}>
          {children}
          {shouldRenderComponent && <NavBAr />}
          <ToastContainer position="bottom-right" closeOnClick={true} rtl />
          <Loading />
          <BottomSheetReport />
          <BottomSheetReportManageShift />

          {openTimePicker && <TimePicker />}
        </body>
      </html>
    </AppContext.Provider>
  );
}
