Untitled

 avatar
unknown
plain_text
a year ago
267 kB
8
Indexable
import React, { Fragment, useEffect, useState } from "react";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import getSchoolAttributeValue from "../../../lib/getSchoolAttributeValue";
import ReactTooltip from "react-tooltip";
import * as Yup from "yup";
import GoogleMapReact from "google-map-react";
import { FaStar, FaMusic, FaBookOpen, FaUniversity, FaSwimmer, FaTableTennis, } from "react-icons/fa";
import { BsCircle, BsGenderFemale, BsGenderMale, BsGenderAmbiguous, } from "react-icons/bs";
import { CgBoy, CgGirl } from "react-icons/bs";
import { GiBoxingGloveSurprise, GiRunningNinja, GiBeachBall, GiMountainClimbing, GiCycling, GiTennisCourt, } from "react-icons/gi";
import { MdSchool, MdInfoOutline, MdSportsFootball, MdSportsGolf, MdSportsHandball, MdSportsHockey, MdSportsRugby, MdSportsSoccer, MdSportsTennis, MdSportsVolleyball, MdOutlineSportsBaseball, MdOutlineSportsBasketball, MdOutlineSportsCricket, MdPalette, MdLocationOn, MdPeopleOutline, } from "react-icons/md";
import { BiInfoCircle, BiDollar } from "react-icons/bi";
import TwDropdown from "./tw-dropdown";
import dynamic from "next/dynamic";
import directus from "../../../lib/directus";
import { ROLE_ID, googleMapStyles } from "../../../lib/constant";
import Calendar from "react-calendar";
import { Dialog, Transition } from "@headlessui/react";
import { MyCheckbox, MyRadioInput, MyTextInput } from "../../formik";
import { XIcon } from "@heroicons/react/solid";
import ConfirmDelete from "../../ConfirmDelete";
import GoogleMapMobile from "../../search/GoogleMapMobile";
const GoogleMapWeb = dynamic(() => import("../../search/GoogleMapWeb"));
const SchoolMarker = dynamic(() => import("../../search/SchoolMarker"));
import FileUploadWithDropArea from "../../FileUploadWithDropArea";
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import FileViewer from "../../FileViewer";
import { days } from "../../../lib/constant";
import { Field, Form, Formik } from 'formik';
import Select from 'react-select';
import { convertTimeTo12HourFormat, getDayString, getMapUrl, getParamValue, getMonthsBetweenDates, getAcademicDate, sendEmail } from "../../../lib/utils";
import ApplySuccessFully from "../../ApplySuccessfully";
import { useMediaQuery } from 'react-responsive'
import LoginModal from "../../authentications/LoginModalGeneric";
import { useRouter } from "next/router";
import { callReadQueryApi } from "../../../lib/callApi";
import moment from "moment";
import {PastDate,tomorrowDateTourEvent } from "../../../lib/utils";

function GetSubjectIcon({ name }) {
  const music = name === "music";
  const drawing = name === "drawing";
  if (music) return <FaMusic className="h-6 w-6  text-gray-700 " />;
  if (drawing) return <MdPalette className="h-6 w-6  text-gray-700 " />;
}
function GetCardHeaderIcon({ name }) {
  const graduation_hat = name === "graduation_hat";
  const school_building = name === "school_building";
  const open_book = name === "open_book";

  if (graduation_hat) return <img src="/images/educationIcon.svg" />;
  if (school_building)
    return <img src="/images/schoolsIcons.svg" className="" />;
  if (open_book) return <img src="/images/admissions-icon.svg" className="" />;
}

function GetCardBodyIcon({ name }) {
  const star = name === "star";
  const location = name === "location";
  const circle = name === "circle";
  const dollar = name === "dollar";

  if (star) return <FaStar className=" h-6 w-6 text-slate-400 " />;
  if (location) return <MdLocationOn className=" h-6 w-6 text-slate-400 " />;
  if (circle)
    return (
      <BsCircle
        className="h-5 w-5  bg-gray-300 text-gray-300 rounded-full border-gray-300"
        aria-hidden="true"
      />
    );
  if (dollar) return <BiDollar className=" h-6 w-6 text-slate-400 font-bold" />;
}

function BasicCard({ header_icon, body_icon, display_name, value }) {
  return (
    <div className="relative rounded-lg border lg:mr-5 mb-3 tab-info ">
      <div className="inline-flex justify-start items-center space-x-2 w-full border-b-gray-300 py-3 bottom-border">
        <GetCardHeaderIcon name={header_icon} />
        <p className="title-tabs">{display_name}</p>
      </div>
      {/* <div className="border-b-2 w-full border-b-gray-300"></div> */}
      <div className="inline-flex items-center space-x-2">
        <GetCardBodyIcon name={body_icon} />

        <p className="text-md text-gray-700 info-school">{value}</p>
      </div>
    </div>
  );
}

function BasicCardIcons({ header_icon, body_icon, display_name, value }) {
  return (
    <div className="relative rounded-lg border lg:mr-5 mb-3 tab-info ">
      <div className="inline-flex justify-start items-center space-x-2 w-full border-b-gray-300 py-3 bottom-border">
        <GetCardHeaderIcon name={header_icon} />
        <p className="title-tabs">{display_name}</p>
      </div>
      {/* <div className="border-b-2 w-full border-b-gray-300"></div> */}
      <div className="inline-flex items-center space-x-2">
        <GetCardBodyIcon name={body_icon} />
        <ReactTooltip />
        <p className="text-md text-gray-700 info-school inline-flex space-x-1 flex-wrap w-full">
          {value.split(",").map((item) => {
            item = item.trim();
            if (item == "") {
              return "";
            }
            // Languages: Arabic,English,French,German,Latin,Mandarin,Russian,Spanish
            if (item == "Arabic")
              return (
                <>
                  <img
                    data-tip
                    data-for="arabic"
                    src="/flags/united-33114.svg"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="arabic"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "English")
              return (
                <>
                  <img
                    src="/flags/united-33115.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="eng"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "French")
              return (
                <>
                  <img
                    src="/flags/france-32967.svg"
                    data-tip
                    data-for="fr"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="fr"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "German")
              return (
                <>
                  <img
                    src="/flags/germany-32989.svg"
                    data-tip
                    data-for="ger"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="ger"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "Latin")
              return (
                <>
                  <img
                    src="/flags/latin-pi.jpg"
                    data-tip
                    data-for="latin"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="latin"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "Mandarin")
              return (
                <>
                  <img
                    src="/flags/china-32942.svg"
                    data-tip
                    data-for="man"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="man"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "Russian")
              return (
                <>
                  <img
                    src="/flags/russia-33064.svg"
                    data-tip
                    data-for="russ"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="russ"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            if (item == "Spanish")
              return (
                <>
                  <img
                    src="/flags/spain-33105.svg"
                    data-tip
                    data-for="spanish"
                    className="h-6 w-6 text-gray-700 cursor-pointer object-cover rounded-full border border-[#DAE2EC]"
                    title={item}
                  />
                  <ReactTooltip
                    id="spanish"
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );

            //gender Boys,Girls,Co-educational
            if (item == "Boys")
              return <CgBoy className="h-6 w-6  text-gray-700 " title={item} />;
            if (item == "Girls")
              return (
                <CgGirl className="h-6 w-6  text-gray-700 " title={item} />
              );
            if (item == "Co-educational")
              return (
                <img
                  src="/images/coeducational.svg"
                  className="h-6 w-6  text-gray-700 "
                  title={item}
                />
              );

            //top universities
            if (display_name == "TOP UNIVERSITIES") {
              let src = "/images/universities/" + item.trim() + ".jpg";
              return (
                <>
                  <img
                    src={src}
                    data-tip
                    data-for={item}
                    className="h-6 w-6  text-gray-700 "
                  />
                  <ReactTooltip
                    id={item}
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            }
            //extra curricular
            if (display_name == "EXTRACURRICULAR") {
              let src = "/images/valueicon/" + item.trim() + ".svg";
              return (
                <>
                  <img
                    src={src}
                    data-tip
                    data-for={item}
                    className="h-6 w-6  text-gray-700 "
                  />
                  <ReactTooltip
                    id={item}
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            }
            //facilities
            if (display_name == "FACILITIES") {
              let src = "/images/valueicon/" + item.trim() + ".svg";
              return (
                <>
                  <img
                    src={src}
                    data-tip
                    data-for={item}
                    className="h-6 w-6  text-gray-700 "
                  />
                  <ReactTooltip
                    id={item}
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            }
            //sports
            if (display_name == "SPORTS") {
              let src = "/images/valueicon/" + item.trim() + ".svg";
              return (
                <>
                  <img
                    src={src}
                    data-tip
                    data-for={item}
                    className="h-6 w-6  text-gray-700 "
                  />
                  <ReactTooltip
                    id={item}
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            }
            //SPECIALIST SUBJECTS IN JS
            if (display_name == "SPECIALIST SUBJECTS IN JS") {
              let src = "/images/valueicon/" + item.trim() + ".svg";
              return (
                <>
                  <img
                    src={src}
                    data-tip
                    data-for={item}
                    className="h-6 w-6  text-gray-700 "
                  />
                  <ReactTooltip
                    id={item}
                    className="sports-tooltip"
                    effect="solid"
                    place="top"
                  >
                    <p>{item}</p>
                  </ReactTooltip>
                </>
              );
            }

            return item;
          })}
        </p>
      </div>
    </div>
  );
}
function BasicListCard({ header_icon, body_icon, display_name, items, attr }) {
  // sort according to the defined csv possible values
  var sorted_items = [];
  let keys = attr.possible_values_list.split(",");
  let sorted_index = 0;
  for (var i = 0; i < keys.length; i++) {
    let values = items.filter(function (item) {
      return item[0] == keys[i];
    });
    if (values.length > 0) {
      sorted_items[sorted_index] = values[0];
      sorted_index += 1;
    }
  }
  const initialValue = sorted_items[0][1];
  const [selectionValue, setSelectionValue] = React.useState(initialValue);

  return (
    <div className="rounded-lg border mr-3 mb-3 items-center admission-boxes">
      <div className="inline-flex justify-between items-center space-x-2 w-full pb-3 bottom-border">
        <div className="flex items-center space-x-2">
          <GetCardHeaderIcon name={header_icon} />
          <p className="title-tabs">{display_name}</p>
        </div>
        <div className="flex items-center space-x-2">
          {/* <MdInfoOutline className="h-5 w-5  text-gray-400 shrink-0 attention" data-for={display_name} data-tip="" /> */}
          <img
            src="/images/infoschool.svg"
            className="h-6 w-6 shrink-0"
            data-for={display_name}
            data-tip=""
          />
          <ReactTooltip
            id={display_name}
            className="attention-tooltip"
            effect="solid"
            place="top"
          >
            <p>Click Here To See Other {display_name} Options</p>
          </ReactTooltip>

          <TwDropdown
            items={sorted_items}
            name={display_name}
            onselect={setSelectionValue}
          />
        </div>
      </div>
      <div className="inline-flex items-center space-x-2">
        <p
          className="text-md text-gray-700 selectionValue"
          title={selectionValue}
        >
          {display_name.split("$").map((dummy) => {
            if (display_name == "TUITION FEES")
              return <span>AED {selectionValue.toLocaleString()}</span>;
            else if (display_name == "ROOM SIZES")
              return (
                <span>
                  {selectionValue.toLocaleString()}
                  <span>
                    M<sup>2</sup>
                  </span>{" "}
                </span>
              );
            else if (display_name == "TOP NATIONALITIES") {
              // British,American,Indian,Emirati,Pakistani,French,Russian,Australian,Chinese
              if (selectionValue == "British")
                return (
                  <img
                    src="/flags/united-33115.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "American")
                return (
                  <img
                    src="/flags/united-33137.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Indian")
                return (
                  <img
                    src="/flags/india-32988.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Emirati")
                return (
                  <img
                    src="/flags/united-33114.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Pakistani")
                return (
                  <img
                    src="/flags/pakistan-33047.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "French")
                return (
                  <img
                    src="/flags/france-32967.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Russian")
                return (
                  <img
                    src="/flags/russia-33064.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Australian")
                return (
                  <img
                    src="/flags/austallia-32912.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              if (selectionValue == "Chinese")
                return (
                  <img
                    src="/flags/china-32942.svg"
                    data-tip
                    data-for="eng"
                    className="h-6 w-6  text-gray-700 cursor-pointer"
                  />
                );
              return <span>{selectionValue}</span>;
            } else if (
              display_name == "ATTAINMENT LEVELS" ||
              display_name == "INSPECTION RATING"
            ) {
              // Outstanding,Very Good,Good,Acceptable,Weak
              if (selectionValue == "Outstanding")
                return <span className="text-lime-500">{selectionValue}</span>;
              if (selectionValue == "Very Good")
                return <span className="text-amber-300">{selectionValue}</span>;
              if (selectionValue == "Good")
                return (
                  <span className="text-orange-400">{selectionValue}</span>
                );
              if (selectionValue == "Acceptable")
                return <span className="text-red-700">{selectionValue}</span>;
              if (selectionValue == "Weak")
                return <span className="text-black">{selectionValue}</span>;
              return <span>{selectionValue}</span>;
            } else
              return (
                <span className="text-md text-gray-700 selectionValue">
                  {selectionValue}
                </span>
              );
          })}
        </p>
      </div>
    </div>
  );
}

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

function SchoolAttributeCard(props) {
  //  {id, status, sort, user_created, date_created, user_updated, date_updated, name, category, subcategory, sortable, searchable, filtered, searchable_advanced, possible_values, possible_enumeration_values, add_all_by_default, default_integer_value, default_text_value, default_date_value, default_boolean_value, default_time_value, default_to_integer_value, default_to_time_value, default_set_value_csv, value_type, collection_type}).

  // the card depends on the attribute collection type; if it is
  let header_icon = "";
  switch (props.attr.category) {
    case "Academic":
      header_icon = "graduation_hat";
      break;
    case "Admissions":
      header_icon = "open_book";
      break;
    case "School":
      header_icon = "school_building";
      break;
    default:
      header_icon = "none";
  }
  switch (props.attr.collection_type) {
    case "multiple_selection":
      const csv = props.values[0].value_set_csv
        ? props.values[0].value_set_csv.replaceAll(",", ", ")
        : "";
      if (props.attr.display_as_icons == true) {
        return (
          <BasicCardIcons
            header_icon={header_icon}
            display_name={props.attr.name.toUpperCase()}
            value={csv}
          />
        );
      } else {
        return (
          <BasicCard
            header_icon={header_icon}
            display_name={props.attr.name.toUpperCase()}
            value={csv}
          />
        );
      }

    case "separate_input":
      const values_list = [];
      props.values.map((schoolAttribute) => {
        const skey = schoolAttribute.key.split("*")[1].trim();
        const svalue = getSchoolAttributeValue(
          schoolAttribute,
          props.attr.value_type
        );
        if (!svalue || svalue === "") {
        } else {
          values_list.push([skey, svalue]);
        }
      });
      if (values_list.length > 0) {
        return (
          <BasicListCard
            header_icon={header_icon}
            body_icon={"circle"}
            display_name={props.attr.name.toUpperCase()}
            items={values_list}
            attr={props.attr}
          />
        );
      }
      break;

    case "range_input":
      const range_values_list = [];
      let from_value = "x";
      let to_value = "x";
      props.values.map((schoolAttribute) => {
        const parts = schoolAttribute.key.split("*");
        if (parts[2].trim() == "from") {
          from_value = getSchoolAttributeValue(
            schoolAttribute,
            props.attr.value_type
          );
        }
        if (parts[2].trim() == "to") {
          to_value = getSchoolAttributeValue(
            schoolAttribute,
            props.attr.value_type
          );
        }

        if (from_value != "x" && to_value != "x") {
          if (from_value != "" || to_value != "") {
            const range_value = from_value + " - " + to_value;
            range_values_list.push([parts[1].trim(), range_value]);
          }
          from_value = "x";
          to_value = "x";
        }
      });
      if (range_values_list.length > 0) {
        return (
          <BasicListCard
            header_icon={header_icon}
            body_icon={"circle"}
            display_name={props.attr.name.toUpperCase()}
            items={range_values_list}
            attr={props.attr}
          />
        );
      }
      break;

    default:
      let single_value = getSchoolAttributeValue(
        props.values[0],
        props.attr.value_type
      );
      return (
        <BasicCard
          header_icon={header_icon}
          display_name={props.attr.name.toUpperCase()}
          value={single_value}
        />
      );
  }
}

const OnCampusEventAndTour = (props) => {
  const isMobile = useMediaQuery({ query: '(max-width: 549px)' })
  return (
    <>
      <div className={`InputsBasicInputFull ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex`}>
        <div className="col-span-2 w-full">
          <label className="labels-children">Address</label>
          <MyTextInput className="children-inputs" name="address" type="text" required={false} placeholder="Address Here" />
        </div>
      </div>
      <div className={`InputsBasicInputFull ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex`}>
        <div className="col-span-2 w-full">
          <label className="labels-children">Google Map Pin</label>
          <input className="children-inputs" id="GmapPin" value={props.googleMapPin} onChange={() => { }} name="google_map_pin" style={{ height: "40px", touchAction: 'manipulation' }} required={true} />
          {/* <MyTextInput className="children-inputs" name="google_map_pin" type="text" required={false} placeholder="" /> */}
        </div>
      </div>
      {!isMobile &&<div className="Map w-full relative mb-3">
        <GoogleMapWeb mapVisible={true} setMapVisible={true} schools={props.schools} setMultiView={"event_view"} setSchoolLocation={props.setSchoolLocation} setLat={props.setLat} setLng={props.setLng} event_location={props.event_location} />
      </div>}
      {isMobile &&  <div className="Map w-full relative mb-3"><GoogleMapMobile
                            mapVisible={true}
                            setMapVisible={true}
                            schools={props.schools}
                            setMultiView={"event_view"}
                            setSchoolLocation={props.setSchoolLocation}
                            setLat={props.setLat}
                            setLng={props.setLng}
                            tour_location={props.event_location}
                          /></div> }
    </>
  )
}

const EventMode = (props) => {
  const isMobile = useMediaQuery({ query: '(max-width: 549px)' })
  return (
    <div className={`Checkboxes ${isMobile ? 'w-full' : 'w-96'} justify-start items-start gap-3 inline-flex`}>
      <div class=" flex" >
        <label class="flex items-center">
          <input onClick={() => props.setEventType("ON CAMPUS")} type="radio" class=" form-radio square-radio" name="radio-group" value="option1" checked={props.eventType == "ON CAMPUS" && true} />
          <span class="ml-2">On Campus</span>
        </label>
        <label class="flex items-center ml-4">
          <input type="radio" onClick={() => props.setEventType("ONLINE")} class="form-radio square-radio" name="radio-group" value="option2" checked={props.eventType == "ONLINE" && true} />
          <span class="ml-2">Online</span>
        </label>
      </div>
    </div>
  )
}

const SchoolTabsSection = (props) => {
  const attributes = props.attributes;
  const schoolِAttributes = props.schoolِAttributes;
  const [schools, setSchools] = useState();
  const [open, setOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [currTab, setCurrTab] = useState("tour");
  const [currTabName, setCurrTabName] = useState("Tour");
  const [showEventTourData, setShowEventTourData] = useState(false);
  const [confirmModel, setConfirmModel] = useState(false);
  const [passport, set_passport] = useState();
  const [isHovered, setIsHovered] = useState(false);
  const [isSaveBtn, setIsSaveBtn] = useState(true)
  const [slotEditMode, setSlotEditMode] = useState()
  const [eventType, setEventType] = useState("ON CAMPUS")
  const [otherType, setOtherType] = useState("Group Tour")
  const [description, setDescription] = useState("")
  const [slotsDetails, setSlotsDetails] = useState([]);
  const [eventsData, setEventsData] = useState()
  const [isPastDate, setIsPastDate] = useState(false)
  const [etAllData, setEtAllData] = useState()
  const [toursData, setToursData] = useState()
  const [eventTourEditData, setEventTourEditData] = useState()
  const [calanderHeder, setCalenderHeader] = useState()
  const [currDate, setCurrDate] = useState(new Date())
  const [modalMeassage, setModalMessage] = useState()
  const [cinfirmLbl, setConfirmLbl] = useState()
  const [cancelLbl, setCancelLbl] = useState()
  const user = directus.storage.get("me");
  const [slotInitialValue, setSlotInitialValue] = useState()
  const [hoveredItemId, setHoveredItemId] = useState(null);
  const userData = JSON.parse(user);
  const [userRole, setUserRole] = useState(userData?.role?.name)
  const [isFieldFocusedStartDate, setIsFieldFocusedStartDate] = useState('');
  const [editedSlotId, setEditedSlotId] = useState([])
  const [newTourData,setNewTourData]= useState([])
  const [newTourSlot,setNewTourSlot]= useState([])
  const [schoolLocation, setSchoolLocation] = useState()
  const [joinConfirmModel, setJoinConfirmModel] = useState(false)
  const [cancelTour, setcancelTour] = useState(false)
  const [authenticated, setAuthenticated] = useState(false);
  const [isButtonEnabled, setIsButtonEnabled] = useState(false);
  const [tourEventMemberValid , setTourEventMemberValid]= useState(false);
  const [EventMemberValid, setEventMemberValid]= useState(false);
  const [startDates, setStartDate] = useState(new Date().toISOString().slice(0, 10));
  let schoolId = getParamValue("schoolid");
  const handleMouseEnter = (itemId) => { setHoveredItemId(itemId); };
  const handleMouseLeave = () => { setHoveredItemId(null); };
  const handleFocusStartDate = () => { setIsFieldFocusedStartDate(true); };
  const handleBlurStartDate = () => { setIsFieldFocusedStartDate(false); };
  const [Lat, setLat] = useState();
  const [Lng, setLng] = useState();
  const [Type, setType] = useState();
  const [googleMapPin, setGoogleMapPin] = useState('');
  const [loading, setLoading] = useState(false);
  console.log("slotNamesslotNamesslotNames",slotsDetails ,loading);
  const slotNames = slotsDetails?.map(slot => slot?.slot?.name);
  const slotNamesString = slotNames?.join(', ');
  const isMobile = useMediaQuery({ query: '(max-width: 549px)' })
  const ADMIN_ROLE = ROLE_ID.find(role => role.name === 'Admin');
  const router = useRouter();
  const paramsData = router.query;
  const oneTourMethod = async (id) => {
    const tourEventsMember = await directus.items("tour_event_members").readByQuery({ filter: { parent: { _eq: userData?.id },tour_event: { status: { _eq: "Draft" }}, status: { _eq: "Draft" } , tour_event: { _eq: id } } })
    if (
      tourEventsMember?.data?.length > 0 && tourEventsMember?.data[0]?.parent === userData?.id
    ) {
      setTourEventMemberValid(true);
    } else {
      setTourEventMemberValid(false);
    }
  }
  const EventMethod = async (id) => {
    const eventMember = await directus.items("event_members").readByQuery({ filter: { parent: { _eq: userData?.id }, status: { _eq: "draft" }, event: { _eq: id } } })
    if (
      eventMember?.data?.length === 0
    ) {
      setEventMemberValid(false);
    } else {
      setEventMemberValid(true);
    }
  }
  const joinEventAndTour = async (id, type) => {
    if (!directus.auth.token) {
      setAuthenticated(true);
      return
    } else {
      setAuthenticated(false);
      try {
        if (type === "event") {
          // const eventMember = await directus.items("event_members").readByQuery({ filter: { parent: { _eq: userData?.id }, status: { _eq: "draft" }, event: { _eq: id } } })
          // if (eventMember?.data?.length == 0) {
          //   setLoading(true)
            const eventData = await directus.items("event_members").createOne({ "event": id, "parent": userData?.id })
            const eventRecord = await directus.items("events").readByQuery({ filter: { id: eventData?.event } })
            let schoolData = await directus.items("directus_users").readByQuery({
              filter: { school: eventRecord?.data[0]?.school, role: ADMIN_ROLE?.id }
            })
            if (schoolData?.data[0]?.id) {
              // Send Notification
              await directus.items("notifications").createOne({
                recipient: schoolData?.data[0]?.id,
                category: "Calendar",
                message: `${userData?.first_name} ${userData?.last_name} is attending ${eventRecord?.data[0]?.name}.`
              }); 
              // Send Mail By Parent Self Add Event
              let variables = {
                parentName: `${userData?.first_name} ${userData?.last_name}`,
                parentEmail : userData?.email,
                eventName : eventRecord?.data[0]?.name,
                schoolName : `${schoolData?.data[0]?.first_name} ${schoolData?.data[0]?.last_name}`,
                eventDate : eventRecord?.data[0]?.event_date,
                eventTime : eventRecord?.data[0]?.event_start_time,
                locationPin : `http://maps.google.com?z=12&t=m&q=@${eventRecord?.data[0]?.location?.coordinates[1]},${eventRecord?.data[0]?.location?.coordinates[0]}`,
              };
              console.log('variables ==', variables)
              let url = "/custom/add-event-by-parent";
              sendEmail(url, variables);
            }
            setLoading(false)
            setConfirmModel(true);
            setConfirmLbl("Go to Calendar")
            setCancelLbl("Stay On School Page")
            setModalMessage("Event has been booked!")
          } else {
            // setJoinConfirmModel(true)
          }
        // } else {
        //   const filt = { id: { _eq: id } }
        //   const allTourEventData = await directus.items("tour_events").readByQuery({ filter: filt })
        //   if (allTourEventData.data.length > 0) {
        //     const userId = userData?.id
        //     const len = allTourEventData?.data.length - 1
        //     allTourEventData?.data?.forEach(async (ele, i) => {
        //       setLoading(true)
        //       const tourEventsMember = await directus.items("tour_event_members").readByQuery({ filter: { parent: { _eq: userData?.id },tour_event: { status: { _eq: "Draft" }}, status: { _eq: "Draft" } , tour_event: { _eq: ele.id } } })
        //       if (tourEventsMember?.data[0]?.status === 'Archived' && tourEventsMember?.data[0]?.parent === userData?.id) {
        //         setcancelTour(true)
        //         setJoinConfirmModel(true)
        //         return
        //       }
        //       if (tourEventsMember?.data?.length > 0) {
        //         setJoinConfirmModel(true)
        //         return
        //       } else if (i == len) {
        //         setConfirmModel(true);
        //         setConfirmLbl("Go to Calendar")
        //         setCancelLbl("Stay On School Page")
        //         setModalMessage("Tour has been booked!")
        //         // Tour Join Send Notification to School
        //         let tourID = await directus.items("tours").readByQuery({ filter: { id: allTourEventData?.data[0]?.tour } })
        //         let schoolData = await directus.items("directus_users").readByQuery({
        //           filter: { school: tourID?.data[0]?.school, role: ADMIN_ROLE?.id }
        //         })
        //         if (schoolData?.data[0]?.id) {
        //           await directus.items("notifications").createOne({
        //             recipient: schoolData?.data[0]?.id,
        //             category: "Calendar",
        //             message: `Tour booked by ${userData?.first_name} ${userData?.last_name}.`
        //           });
        //         }
        //       }
        //       const cancelledTourEventsMember = await directus.items("tour_event_members").readByQuery({ filter: { status: { _eq: "Draft" } , tour_event: { status: { _eq: "Draft" }} , parent: { _eq: userData?.id }, tour_event: { _eq: ele.id } } })
        //       if (cancelledTourEventsMember?.data?.length > 0) {
        //         await directus.items("tour_event_members").updateOne(cancelledTourEventsMember?.data[0].id, { status: "Draft" })
        //       } else {
        //         const tourEventMemberRes = await directus.items("tour_event_members").createOne({
        //           "tour_event": ele.id,
        //           "parent": userId,
        //           "status": "Draft"
        //         })
        //       }
        //       setLoading(false)
        //     })
        //   } else {
        //     console.log('allTourEventData length NULL ==')
        //   }

        // }

      } catch (e) {
        console.log('error ==>', e)
      }
    }
  }

  // Create Slot
  const handleCreateSlots = async (values,type) => {
    console.log("slot Values ==", values.values, "type.......",type);

    let slotValue = values
    const requiredFields = ['slot_name', 'slot_start_date', 'slot_end_time', 'slot_start_time'];

    if (requiredFields.some(field => !slotValue[field] || (Array.isArray(slotValue[field]) && slotValue[field].length === 0))) {
      console.log("Please Input all fields in slots ==");
      return;
    }

    try {
      setSlotEditMode(false)
      const eventDate = new Date(slotValue.slot_start_date)
      const month = eventDate.getMonth()
      const year = eventDate.getFullYear()
      const dayOfMonth = eventDate.getDate();
      const weekOfMonth = Math.ceil(dayOfMonth / 7);

      const monthYears = getMonthsBetweenDates(slotValue.slot_start_date, slotValue.slot_end_date)
      const weekdays = slotValue?.weekdays?.map(day => day);
      const slot = {
        name: slotValue.slot_name,
        weekdays: weekdays,
        slot_start_date: slotValue.slot_start_date,
        slot_end_date: slotValue.slot_end_date,
        slot_start_time: slotValue.slot_start_time,
        slot_end_time: slotValue.slot_end_time,
        month: month + 1,
        year: year,
        week: weekOfMonth,
        month_years: monthYears,
        status: 'Draft'
      }

      slotValue.slot_id ? slot.id = slotValue.slot_id : slot.tempId = new Date().getTime()
      if ( slot?.tempId && (type == "NewSlot" || type == "EditInCreateNewTour")) {
        const tempSlot = slot;
        const startDate = slot.slot_start_date;
        const endDate = slot.slot_end_date;
        const weekDays = slot?.weekdays;
        let createdRecordsCount = 0;
        let resultWithEndDate = [];
        let resultWithoutEndDate = [];
        if (endDate == '' || endDate == undefined) {
          resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
        } else {
          resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
        }
        const newTour = await directus.items("slots").createOne(slot)
        newTourData.push(newTour)
        setNewTourSlot(slot)
        setNewTourData(newTourData)
      } else {
        if (slotsDetails?.length > 0) {
          const data = slotsDetails?.map(item => {
            const x = {
              ...item,
              slot: item.slot && item.slot.id === slot.id ? slot : item.slot
            };
            return x
          }
          );
          setSlotsDetails(data)
        }
        if(newTourData?.length > 0 && type == "NewEditSlot") {
          const editNewTourData =  newTourData?.map((i)=>{
            return  i?.id === slot.id ? slot : i
          })
          setNewTourData(editNewTourData)
        }
      }
      setIsSaveBtn(false);
    } catch (err) {
      console.log("error on create slot ==", err);
    }
  }

  const handleAddslotClick = () => {
    setSlotInitialValue()
    setIsSaveBtn(true)
  };
  // Slot Update
  const handleScheduleEditClick = (data, type) => {
    if (type === "Slot Update" || type === "NewSlot") {
      !editedSlotId.includes(data?.id) && setEditedSlotId([...editedSlotId, data?.id])
    }
    if (!slotEditMode) {
      setIsSaveBtn(false)
      setSlotEditMode(true)
      const uniqueSlotIds = new Set();
      const uniqueData = slotsDetails ? slotsDetails : [].filter(item => {
        if (!uniqueSlotIds.has(item?.slot?.id)) {
          uniqueSlotIds.add(item?.slot?.id);
          return true;
        }
        return false;
      });
      const slotsData = uniqueData.filter((m) => { return m.tempId !== data?.tempId || m.id !== data?.id })
      // setNewTourData(newTourData)
      setSlotsDetails(slotsData)
      const tempData = {
        slotName: data?.name,
        weekdays: data?.weekdays,
        slotStartDate: data?.slot_start_date,
        slotEndDate: data?.slot_end_date,
        slotStartTime: data?.slot_start_time,
        slotEndTime: data?.slot_end_time
      }

      if (data?.id) {
        tempData.id = data.id
      }
      console.log("tempData..setSlotInitialValue...",tempData);
      setSlotInitialValue(tempData)
    }
  }

  // Google Map Link To convert in Lat-Long Coordinates
  const extractCoordinates = (url) => {
    const regex = /@(-?\d+\.\d+),(-?\d+\.\d+)/; // Regex to match latitude and longitude
    const matches = url.match(regex);
    if (matches && matches.length >= 3) {
      const lat = parseFloat(matches[1]);
      const lng = parseFloat(matches[2]);
      return { coordinates: [lng, lat], type: "Point" };
    }
    return null;
  };

  // Store Event
  const handleEventSubmit = async (values) => {
    try {
      const eventStartDate = new Date(values.event_date)
      const startTimeSplit = values.event_start_time.toString().split(":")
      eventStartDate.setHours(startTimeSplit[0])
      eventStartDate.setMinutes(startTimeSplit[1])
      const eventEndDate = new Date(values.event_date)
      const endTimeSplit = values.event_end_time.toString().split(":")
      eventEndDate?.setHours(endTimeSplit[0])
      eventEndDate?.setMinutes(endTimeSplit[1])
      const eventDate = new Date(values.event_date)
      const month = eventDate.getMonth()
      const year = eventDate.getFullYear()
      const dayOfMonth = eventDate.getDate();
      const weekOfMonth = Math.ceil(dayOfMonth / 7);
      const locationCoordinates = extractCoordinates(googleMapPin);
      const result = await directus.items("events").createOne({
        "school": userData?.school,
        "school_representative": userData.id,
        "banner": passport,
        "name": values.name,
        "event_date": eventDate,
        "event_start_time": values.event_start_time,
        "event_end_time": values.event_end_time,
        "event_start_date_time": eventStartDate.toString(),
        "event_end_date_time": eventEndDate.toString(),
        "month": month + 1,
        "year": year,
        "week": weekOfMonth,
        "event_mode": eventType,
        "address": values.address,
        "description": description,
        "fully_booked": false,
        "is_active": true,
        "meeting_url": values.meeting_url,
        "location": locationCoordinates,
        "members": null
      });
      console.log("Event Submit Result : ==", result);
      setConfirmModel(true)
      setConfirmLbl("Go to Calendar")
      setCancelLbl("Stay On School Page")
      setModalMessage("Event Created Successfully!!")
      return result;
    } catch (error) {
      console.log("error On Event ==", error);
    }
  };

  // Tour Week Days Count
  function getDatesBetween(startDate, endDate, weekdays) {
    if (!endDate) {
      const current = new Date(startDate);
      endDate = new Date(current);
      endDate.setFullYear(current.getFullYear() + 1);
    }

    const dates = [];
    const current = new Date(startDate);
    const end = new Date(endDate);

    while (current <= end) {
      const dayOfWeek = current.toLocaleDateString('en-US', { weekday: 'short' });

      if (weekdays.includes(dayOfWeek)) {
        if (current) {
          dates.push(current.toISOString().slice(0, 10));
        }
      }

      current.setDate(current.getDate() + 1);
    }
    return dates;
  }

  // Store Tour 
  const handleTourSubmit = async (values) => {
    console.log('Tour values ==', values)

    const TourlocationCoordinates = extractCoordinates(googleMapPin);
    try {
      // Tour API
      const result = await directus.items("tours").createOne({
        "school": userData?.school,
        "user_created": userData?.id,
        "event_mode": eventType,
        "address": values.address,
        "fully_booked": false,
        "is_active": true,
        "meeting_url": values.meeting_url,
        "location": TourlocationCoordinates,
        "tour_type": otherType,
        "description": description,
      });
      // Slot API
      console.log("handleTourSubmit slotsDetails....",slotsDetails);
      if(slotsDetails){
        slotsDetails.map(async (slot) => {
          const tempSlot = slot?.slot;
          tempSlot.tour = result.id;
          const startDate = slot?.slot.slot_start_date;
          const endDate = slot?.slot.slot_end_date;
          const weekDays = slot?.slot?.weekdays;
          let createdRecordsCount = 0;
          let resultWithEndDate = [];
          let resultWithoutEndDate = [];
          if (endDate == '' || endDate == undefined) {
            resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
          } else {
            resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
          }
          const slotResult = await directus.items("slots").createOne(tempSlot)
          console.log("++ resultWithoutEndDate ==", resultWithoutEndDate);
          console.log("-- resultWithEndDate ==", resultWithEndDate);
            const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
            dates.map( async (i)=>{
              const eventStartDate = new Date(i)
              const startTimeSplit = slot?.slot.slot_start_time.toString().split(":")
              eventStartDate.setHours(startTimeSplit[0])
              eventStartDate.setMinutes(startTimeSplit[1])
              const eventEndDate = new Date(i)
              const endTimeSplit = slot?.slot?.slot_end_time?.toString()?.split(":")
              // const endTimeSplit = values?.slot_end_time?.toString()?.split(":")
              eventEndDate?.setHours(endTimeSplit[0])
              eventEndDate?.setMinutes(endTimeSplit[1])
              const data = {
                tour_date: i,
                tour: result.id,
                slot: slotResult.id,
                tour_event_start_date_time: eventStartDate.toString(),
                tour_event_end_date_time: eventEndDate.toString(),
              };
              const tourEventsRes = await directus.items("tour_events").createOne(data);
              console.log('tourEvents Store Res ==>', tourEventsRes)
              createdRecordsCount++;
            })
            console.log("Total Tour Slot Records Created: ==", createdRecordsCount);
          });
      }
      // const newObjectWithoutId = (({ id, ...rest }) => rest)(newTourData);
      if(newTourData){
        newTourData?.map(async (slot) => {
          const tempSlot = slot;
          tempSlot.tour = result?.id;
          const startDate = slot?.slot_start_date;
          const endDate = slot?.slot_end_date;
          const weekDays = slot?.weekdays;
          let createdRecordsCount = 0;
          let resultWithEndDate = [];
          let resultWithoutEndDate = [];
          if (endDate == '' || endDate == undefined) {
            resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
          } else {
            resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
          }
          // const slotResult = await directus.items("slots").createOne(tempSlot)
          console.log("++ resultWithoutEndDate ==", resultWithoutEndDate);
          console.log("-- resultWithEndDate ==", resultWithEndDate);
          console.log("slotslotslot...///.....",slot);
            const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
            dates?.map( async (i)=>{
                const eventStartDate = new Date(i)
                const startTimeSplit = slot?.slot_start_time.toString().split(":")
                eventStartDate.setHours(startTimeSplit[0])
                eventStartDate.setMinutes(startTimeSplit[1])
                const eventEndDate = new Date(i)
                const endTimeSplit = slot?.slot_end_time?.toString()?.split(":")
                // const endTimeSplit = values?.slot_end_time?.toString()?.split(":")
                eventEndDate?.setHours(endTimeSplit[0])
                eventEndDate?.setMinutes(endTimeSplit[1])
                const data = {
                  tour_date: i,
                  tour: result?.id,
                  slot: slot?.id,
                  tour_event_start_date_time: eventStartDate.toString(),
                  tour_event_end_date_time: eventEndDate.toString(),
                };
                const tourEventsRes = await directus.items("tour_events").createOne(data);
                console.log("tourEventsRes......",tourEventsRes);
              })
        })
      }
      setConfirmModel(true)
      setConfirmLbl("Go to Calendar")
      setCancelLbl("Stay On School Page")
      setModalMessage("Tour Created Successfully!!")
      return result;
    } catch (error) {
      console.log("error On Event ==", error);
    }
  };

  // Event Update
  const handleEditClick = async (values, type) => {
    const eventDate = new Date(values.event_date)
    const month = eventDate.getMonth()
    const year = eventDate.getFullYear()
    const dayOfMonth = eventDate.getDate();
    const weekOfMonth = Math.ceil(dayOfMonth / 7);
    const locationCoordinates = extractCoordinates(googleMapPin);

    const eventStartDate = new Date(values.event_date)
    const startTimeSplit = values.event_start_time.toString().split(":")
    eventStartDate.setHours(startTimeSplit[0])
    eventStartDate.setMinutes(startTimeSplit[1])
    const eventEndDate = new Date(values.event_date)
    const endTimeSplit = values.event_end_time.toString().split(":")
    eventEndDate.setHours(endTimeSplit[0])
    eventEndDate.setMinutes(endTimeSplit[1])

    try {
      const result = await directus.items("events").updateOne(eventTourEditData.id, {
        "banner": passport,
        "name": values.name,
        "event_start_time": values.event_start_time,
        "event_end_time": values.event_end_time,
        "event_start_date_time": eventStartDate.toString(),
        "event_end_date_time": eventEndDate.toString(),
        "event_date": eventDate,
        "month": month + 1,
        "year": year,
        "week": weekOfMonth,
        "event_mode": eventType,
        "address": values.address,
        "description": description,
        "fully_booked": values.fully_booked,
        "is_active": true,
        "meeting_url": values.meeting_url,
        "location": locationCoordinates,
        "members": null
      });
      setConfirmModel(true)
      setConfirmLbl("Go to Calendar")
      setCancelLbl("Stay On School Page")
      setModalMessage("Event Edited Successfully!!")
    } catch (e) {
      console.log('edit event error ==>', e)
    }
  }

  // Tour Update
  const handleTourEdit = async (values) => {
    try {
      // Edit Tour inside New Slot Will Create
      try {
        const editableNewSlot = slotsDetails.filter((f) => { return f.slot.tempId })
        const editableTourDataNewSlot = [newTourSlot].filter((f) => { return f.tempId })
        if (editableNewSlot) {
          editableNewSlot.map(async (slot) => {
            console.log('New Editable slot  ==', slot)
            const tempSlot = slot;
            tempSlot.tour = eventTourEditData?.id;
            const startDate = slot.slot_start_date;
            const endDate = slot.slot_end_date;
            const weekDays = slot?.weekdays;
            let createdRecordsCount = 0;
            let resultWithEndDate = [];
            let resultWithoutEndDate = [];
            if (endDate == '' || endDate == undefined) {
              resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
            } else {
              resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
            }
            const slotResult = await directus.items("slots").createOne(tempSlot)
            console.log("-- resultWithoutEndDate ==", resultWithoutEndDate);
            console.log("++ resultWithEndDate ==", resultWithEndDate);
            if (dates.length !== 0) {
              filterTourEventsData?.data?.map((i) => {
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, {
                    status: "Archived",
                  });
              })
              const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
              dates.map(async (dateEle) => {
                const eventStartDate = new Date(dateEle)
                const startTimeSplit = slot.slot_start_time.toString().split(":")
                eventStartDate.setHours(startTimeSplit[0])
                eventStartDate.setMinutes(startTimeSplit[1])
                const eventEndDate = new Date(dateEle)
                const endTimeSplit = slot.slot_end_time.toString().split(":")
                eventEndDate.setHours(endTimeSplit[0])
                eventEndDate.setMinutes(endTimeSplit[1])
                const data = {
                  tour_date: dateEle,
                  tour: eventTourEditData.id,
                  slot: slotResult.id,
                  tour_event_start_date_time: eventStartDate.toString(),
                  tour_event_end_date_time: eventEndDate.toString(),
                };
                await directus.items("tour_events").createOne(data);
              })
            }
            else {
              filterTourEventsData?.data?.map((i) => {
                const dateObject = new Date(i?.tour_event_start_date_time);

                // Extract year, month, and day
                const year = dateObject.getFullYear();
                const month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based
                const day = dateObject.getDate().toString().padStart(2, '0');

                // Form the desired date string
                const outputDateString = `${year}-${month}-${day}`;
                const startTime = i?.tour_event_start_date_time
                const endTime = i?.tour_event_end_date_time
                const newStartTime = editableSlot[0]?.slot_start_time
                const newEndTime = editableSlot[0]?.slot_end_time
                const originalStartDate = new Date(startTime);
                const originalEndDate = new Date(endTime);
                const dateStartPart = originalStartDate.toDateString();
                const dateEndPart = originalEndDate.toDateString();
                const newStartDateString = `${dateStartPart} ${newStartTime} GMT+0530 (India Standard Time)`;
                const newEndDateString = `${dateEndPart} ${newEndTime} GMT+0530 (India Standard Time)`;
                const data = {
                  tour_date: outputDateString,
                  tour_event_start_date_time: newStartDateString,
                  tour_event_end_date_time: newEndDateString
                }
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, data);
              })
            }
          })
        }
        if (editableTourDataNewSlot ) {
          editableTourDataNewSlot.map(async (slot) => {
            const slotResult = await directus.items("slots").createOne(slot);
            const filtr = { slot: { _eq: slotResult.id } }
            const filterTourEventsData = await directus.items("tour_events").readByQuery({ filter: filtr })
            const startDate = slot?.slot_start_date;
            const endDate = slot?.slot_end_date;
            const weekDays = slot?.weekdays;
            let resultWithEndDate = [];
            let resultWithoutEndDate = [];
            if (endDate == '' || endDate == undefined) {
              resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
            } else {
              resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
            }
            console.log("slotResult....", slotResult);
            console.log("resultWithoutEndDate.....///....", resultWithoutEndDate);
            console.log("resultWithEndDate..===...", resultWithEndDate);
            const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
            if (dates.length !== 0) {
              filterTourEventsData?.data?.map((i) => {
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, {
                    status: "Archived",
                  });
              })
              dates.map(async (dateEle) => {
                const eventStartDate = new Date(dateEle)
                const startTimeSplit = slot.slot_start_time.toString().split(":")
                eventStartDate.setHours(startTimeSplit[0])
                eventStartDate.setMinutes(startTimeSplit[1])
                const eventEndDate = new Date(dateEle)
                const endTimeSplit = slot.slot_end_time.toString().split(":")
                eventEndDate.setHours(endTimeSplit[0])
                eventEndDate.setMinutes(endTimeSplit[1])
                const data = {
                  tour_date: dateEle,
                  tour: eventTourEditData.id,
                  slot: slotResult.id,
                  tour_event_start_date_time: eventStartDate.toString(),
                  tour_event_end_date_time: eventEndDate.toString(),
                };
                await directus.items("tour_events").createOne(data);
              })
            }
            else {
              filterTourEventsData?.data?.map((i) => {
                const dateObject = new Date(i?.tour_event_start_date_time);

                // Extract year, month, and day
                const year = dateObject.getFullYear();
                const month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based
                const day = dateObject.getDate().toString().padStart(2, '0');

                // Form the desired date string
                const outputDateString = `${year}-${month}-${day}`;
                const startTime = i?.tour_event_start_date_time
                const endTime = i?.tour_event_end_date_time
                const newStartTime = editableSlot[0]?.slot_start_time
                const newEndTime = editableSlot[0]?.slot_end_time
                const originalStartDate = new Date(startTime);
                const originalEndDate = new Date(endTime);
                const dateStartPart = originalStartDate.toDateString();
                const dateEndPart = originalEndDate.toDateString();
                const newStartDateString = `${dateStartPart} ${newStartTime} GMT+0530 (India Standard Time)`;
                const newEndDateString = `${dateEndPart} ${newEndTime} GMT+0530 (India Standard Time)`;
                const data = {
                  tour_date: outputDateString,
                  tour_event_start_date_time: newStartDateString,
                  tour_event_end_date_time: newEndDateString
                }
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, data);
              })
            }
          })
        }
      } catch (error) {
        console.log('Catch error Edit New Slot ==', error)
      }
      // Particular Tour Slot Update
      try {
        const editableSlot = slotsDetails.filter((f) => { return editedSlotId.includes(f.slot.id) })
        const editableNewSlot = newTourData.filter((f) => { return editedSlotId.includes(f.id) })
        if (slotsDetails && editableSlot && editedSlotId) {
          editableSlot?.map(async (slot) => {
            const slotResult = await directus.items("slots").updateOne(slot.slot.id, slot.slot)
            const filtr = { slot: { id: { _eq: slot.slot.id } } }
            const filterTourEventsData = await directus.items("tour_events").readByQuery({ filter: filtr })
            const startDate = slot?.slot.slot_start_date;
            const endDate = slot?.slot.slot_end_date;
            const weekDays = slot?.slot?.weekdays;
            let resultWithEndDate = [];
            let resultWithoutEndDate = [];
            if (endDate == '' || endDate == undefined) {
              resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
            } else {
              resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
            }
            console.log("slotResult....", slotResult);
            console.log("resultWithoutEndDate.....///....", resultWithoutEndDate);
            console.log("resultWithEndDate..===...", resultWithEndDate);
            const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
            console.log("filterTourEventsData.....", filterTourEventsData);
            console.log("dates......", dates);
            if (dates.length !== 0) {
              filterTourEventsData?.data?.map((i) => {
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, {
                    status: "Archived",
                  });
              })
              dates.map(async (dateEle) => {
                const eventStartDate = new Date(dateEle)
                const startTimeSplit = slot.slot.slot_start_time.toString().split(":")
                eventStartDate.setHours(startTimeSplit[0])
                eventStartDate.setMinutes(startTimeSplit[1])
                const eventEndDate = new Date(dateEle)
                const endTimeSplit = slot.slot.slot_end_time.toString().split(":")
                eventEndDate.setHours(endTimeSplit[0])
                eventEndDate.setMinutes(endTimeSplit[1])
                const data = {
                  tour_date: dateEle,
                  tour: eventTourEditData.id,
                  slot: slotResult.id,
                  tour_event_start_date_time: eventStartDate.toString(),
                  tour_event_end_date_time: eventEndDate.toString(),
                };
                await directus.items("tour_events").createOne(data);
              })
            } else {
              filterTourEventsData?.data?.map((i) => {
                const dateObject = new Date(i?.tour_event_start_date_time);

                // Extract year, month, and day
                const year = dateObject.getFullYear();
                const month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based
                const day = dateObject.getDate().toString().padStart(2, '0');

                // Form the desired date string
                const outputDateString = `${year}-${month}-${day}`;
                const startTime = i?.tour_event_start_date_time
                const endTime = i?.tour_event_end_date_time
                const newStartTime = editableSlot[0]?.slot?.slot_start_time
                const newEndTime = editableSlot[0]?.slot?.slot_end_time
                const originalStartDate = new Date(startTime);
                const originalEndDate = new Date(endTime);
                const dateStartPart = originalStartDate.toDateString();
                const dateEndPart = originalEndDate.toDateString();
                const newStartDateString = `${dateStartPart} ${newStartTime} GMT+0530 (India Standard Time)`;
                const newEndDateString = `${dateEndPart} ${newEndTime} GMT+0530 (India Standard Time)`;
                const data = {
                  tour_date: outputDateString,
                  tour_event_start_date_time: newStartDateString,
                  tour_event_end_date_time: newEndDateString
                }
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, data);
              })
            }
          })
        }
        if (newTourData.length >= 0  && editableNewSlot && editedSlotId && slotsDetails.length <= 0) {
          editableNewSlot.map(async (slot) => {
            const slotResult = await directus.items("slots").updateOne(slot.id, slot)
            const filtr = { slot: { _eq: slot.id } }
            const filterTourEventsData = await directus.items("tour_events").readByQuery({ filter: filtr })
            const startDate = slot?.slot_start_date;
            const endDate = slot?.slot_end_date;
            const weekDays = slot?.weekdays;
            let resultWithEndDate = [];
            let resultWithoutEndDate = [];
            if (endDate == '' || endDate == undefined) {
              resultWithoutEndDate = getDatesBetween(startDate, "", weekDays);
            } else {
              resultWithEndDate = getDatesBetween(startDate, endDate, weekDays);
            }
            console.log("slotResult....", slotResult);
            console.log("resultWithoutEndDate.....///....", resultWithoutEndDate);
            console.log("resultWithEndDate..===...", resultWithEndDate);
            const dates = endDate ? resultWithEndDate : resultWithoutEndDate;
            if (dates.length !== 0) {
              filterTourEventsData?.data?.map((i) => {
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, {
                    status: "Archived",
                  });
              })
              dates.map(async (dateEle) => {
                const eventStartDate = new Date(dateEle)
                const startTimeSplit = slot.slot_start_time.toString().split(":")
                eventStartDate.setHours(startTimeSplit[0])
                eventStartDate.setMinutes(startTimeSplit[1])
                const eventEndDate = new Date(dateEle)
                const endTimeSplit = slot.slot_end_time.toString().split(":")
                eventEndDate.setHours(endTimeSplit[0])
                eventEndDate.setMinutes(endTimeSplit[1])
                const data = {
                  tour_date: dateEle,
                  tour: eventTourEditData.id,
                  slot: slotResult.id,
                  tour_event_start_date_time: eventStartDate.toString(),
                  tour_event_end_date_time: eventEndDate.toString(),
                };
                console.log("data.....", data);
                await directus.items("tour_events").createOne(data);
              })
            }
            else {
              filterTourEventsData?.data?.map((i) => {
                const dateObject = new Date(i?.tour_event_start_date_time);

                // Extract year, month, and day
                const year = dateObject.getFullYear();
                const month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based
                const day = dateObject.getDate().toString().padStart(2, '0');

                // Form the desired date string
                const outputDateString = `${year}-${month}-${day}`;
                const startTime = i?.tour_event_start_date_time
                const endTime = i?.tour_event_end_date_time
                const newStartTime = editableSlot[0]?.slot_start_time
                const newEndTime = editableSlot[0]?.slot_end_time
                const originalStartDate = new Date(startTime);
                const originalEndDate = new Date(endTime);
                const dateStartPart = originalStartDate.toDateString();
                const dateEndPart = originalEndDate.toDateString();
                const newStartDateString = `${dateStartPart} ${newStartTime} GMT+0530 (India Standard Time)`;
                const newEndDateString = `${dateEndPart} ${newEndTime} GMT+0530 (India Standard Time)`;
                const data = {
                  tour_date: outputDateString,
                  tour_event_start_date_time: newStartDateString,
                  tour_event_end_date_time: newEndDateString
                }
                return directus
                  .items("tour_events")
                  .updateOne(i?.id, data);
              })
            }
          })
        }

      } catch (error) {
        console.log('Edit Particular Slot error ==', error)
      }
    } catch (e) {
      console.log('error ==>', e)
    }

    try {
      const TourlocationCoordinates = extractCoordinates(googleMapPin);
      const result = await directus.items("tours").updateOne(eventTourEditData.id, {
        "event_mode": eventType,
        "address": values.address,
        "description": description,
        "fully_booked": values.fully_booked,
        "is_active": true,
        "meeting_url": values.meeting_url,
        "location": TourlocationCoordinates,
        "members": null,
        "tour_type": otherType,
      });

      setConfirmModel(true)
      setConfirmLbl("Go to Calendar")
      setCancelLbl("Stay On School Page")
      setModalMessage("Tour Updated Successfully!!")
    } catch (e) {
      console.log('edit event error ==>', e)
    }
  }

  const handleTabChange = async (tabName) => {
    try {
      const tempDate = new Date(currDate)
      let slotFilter
      let filtr
      const monthYear = `${tempDate.getMonth() + 1}-${tempDate.getFullYear()}`
      // if (userRole === "Parent") {
      if (schoolId) {
        slotFilter = { tour: { school: { _eq: schoolId }, }, month_years: { _contains: monthYear }, status: { _eq: "Draft" } }
        filtr = { school: { _eq: schoolId }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
      } else {
        slotFilter = { tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school } }, month_years: { _contains: monthYear }, status: { _eq: "Draft" } }
        filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
      }

      if (tabName === "tour") {
        let tourFilter,eventTable;
        let fields = []
        // const slots = await directus.items("slots").readByQuery({ filter: slotFilter, fields: ["tour.*", "*"], sort: ['-slot_start_date'] })
        // const filteredSlot = slots?.data?.filter((ele) => { return ele.tour.status !== "archived" })
        // setToursData(filteredSlot)
        tourFilter = { _and: [{ tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }} },{ slot :{month_years: { _contains: monthYear }}},{ status: { _eq: "Draft" } }] };
        eventTable = "tour_events";
        fields = ["*", "tour.school.*", "slot.*", "tour.*"];
        const tours = await callReadQueryApi(eventTable, tourFilter, fields, ['tour_date'], -1)
        const filteredSlot = tours?.filter((ele) => { 
          const apiMonth = moment(ele?.tour_date).month() + 1 
          const apiYear = moment(ele?.tour_date).year()  
          return tempDate.getMonth()+1 === apiMonth && tempDate.getFullYear() === apiYear
        })
        setToursData(filteredSlot)
      } else {
        const events = await directus.items("events").readByQuery({ filter: filtr, sort: ['-event_date'] },)
        setEventsData(events?.data)
      }
    } catch (e) {
      console.log('error ==>', e)
    }
  }

  // Calendar Previous Month Btn Click
  const handleBackClick = async () => {
    const tempDate = new Date(currDate)
    tempDate.setMonth(tempDate.getMonth() - 1);

    const monthName = tempDate.toLocaleString('default', { month: 'long' });
    const fullYear = tempDate.getFullYear()

    const currentDate = new Date();
    const targetDate = new Date(`${monthName} ${fullYear}`);
    if (targetDate > currentDate) {
      setIsButtonEnabled(true);
    } else {
      setIsButtonEnabled(false);
    }
    try {
      const tempDate = new Date(currDate)
      tempDate.setMonth(tempDate.getMonth() - 1);
      setCurrDate(tempDate)
      const monthName = tempDate.toLocaleString('default', { month: 'long' });
      const fullYear = tempDate.getFullYear()
      setCalenderHeader(`${monthName} ${fullYear}`)
      const monthYear = `${tempDate.getMonth() + 1}-${tempDate.getFullYear()}`
      let filtr
      let slotFilter
      // if (userRole === "Parent") {
      if (schoolId) {
        slotFilter = { tour: { school: { _eq: schoolId }, }, month_years: { _contains: monthYear } }
        filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
      }
      else {
        filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
        slotFilter = { tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school } }, month_years: { _contains: monthYear } }
      }


      if (currTabName === "Tour") {
        let tourFilter, fields ,eventTable
        // const slots = await directus.items("slots").readByQuery({ filter: slotFilter, fields: ["tour.*", "*"], sort: ['-slot_start_date'] })
        // const filteredSlot = slots?.data?.filter((ele) => { return ele.tour.status !== "archived" })
        // setToursData(filteredSlot)
        tourFilter = { _and: [{ tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }} },{ slot :{month_years: { _contains: monthYear }}},{ status: { _eq: "Draft" } }] };
        eventTable = "tour_events";
        fields = ["*", "tour.school.*", "slot.*", "tour.*"];
        const tours = await callReadQueryApi(eventTable, tourFilter, fields, ['tour_date'], -1)
        const filteredSlot = tours?.filter((ele) => { 
          const apiMonth = moment(ele?.tour_date).month() + 1 
          const apiYear = moment(ele?.tour_date).year()  
          return tempDate.getMonth()+1 === apiMonth && tempDate.getFullYear() === apiYear
        })
        setToursData(filteredSlot)
      } else {
        const events = await directus.items("events").readByQuery({ filter: filtr, sort: ['-event_date'], })
        setEventsData(events?.data)
      }

    } catch (e) {
      console.log('error ==>', e)
    }
  }

  // Calendar Next Month Btn Click
  const handleNextMonthClick = async () => {
    const tempDate = new Date(currDate)
    tempDate.setMonth(tempDate.getMonth() + 1);
   
    const monthName = tempDate.toLocaleString('default', { month: 'long' });
    const fullYear = tempDate.getFullYear()
  
      const currentDate = new Date();
    const targetDate = new Date(`${monthName} ${fullYear}`);

    if (targetDate > currentDate) {
      setIsButtonEnabled(true);
    } else {
      setIsButtonEnabled(false);
    }
    try {
      const tempDate = new Date(currDate)
      tempDate.setMonth(tempDate.getMonth() + 1);
      setCurrDate(tempDate)
      const monthName = tempDate.toLocaleString('default', { month: 'long' });
      const fullYear = tempDate.getFullYear()
      setCalenderHeader(`${monthName} ${fullYear}`)
      const monthYear = `${tempDate.getMonth() + 1}-${tempDate.getFullYear()}`
      let filtr
      let slotFilter
      // if (userRole === "Parent") {
      if (schoolId) {
        slotFilter = { tour: { school: { _eq: schoolId }, }, month_years: { _contains: monthYear } }
        filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
      }
      else {
        slotFilter = { tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school } }, month_years: { _contains: monthYear } }
        filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
      }


      if (currTabName === "Tour") {
        let tourFilter, fields ,eventTable
        // const slots = await directus.items("slots").readByQuery({ filter: slotFilter, fields: ["tour.*", "*"], sort: ['-slot_start_date'] })
        // const filteredSlot = slots?.data?.filter((ele) => { return ele.tour.status !== "archived" })
        // setToursData(filteredSlot)
        tourFilter = { _and: [{ tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }} },{ slot :{month_years: { _contains: monthYear }}},{ status: { _eq: "Draft" } }] };
        eventTable = "tour_events";
        fields = ["*", "tour.school.*", "slot.*", "tour.*"];
        const tours = await callReadQueryApi(eventTable, tourFilter, fields, ['tour_date'], -1)
        const filteredSlot = tours?.filter((ele) => { 
          const apiMonth = moment(ele?.tour_date).month() + 1 
          const apiYear = moment(ele?.tour_date).year()  
          return tempDate.getMonth()+1 === apiMonth && tempDate.getFullYear() === apiYear
        })
        setToursData(filteredSlot)
      } else {
        const events = await directus.items("events").readByQuery({ filter: filtr, sort: ['-event_date'] })
        setEventsData(events?.data)
      }
    } catch (e) {
      console.log('error ==>', e)
    }
  }

  const confirmClick = () => {
    setConfirmModel(false);
    window.location.reload()
  };

  const handleAddEvent = () => {
    setSlotInitialValue()
    setSlotsDetails()
    set_passport()
    setDescription("")
    setOpen(true);
  };

  // Edit (Event-Tour) default Selected Val In Modal
  const handleEditEvent = async (id, type) => {
    if (type === "events") {
      let event = await directus.items("events").readOne(id)
      set_passport(event.banner)
      setDescription(event.description)
      setEventType(event.event_mode)
      const date = new Date(event.event_date);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
      const day = String(date.getDate()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;
      event.event_date = formattedDate
      const updatedMapPin = `http://maps.google.com?z=12&t=m&q=@${event?.location?.coordinates[1]},${event?.location?.coordinates[0]}`;
      setGoogleMapPin(updatedMapPin)
      setEventTourEditData(event)
      setType("event")
    }
    else if (type === "tours") {
      const tour = await directus.items("tours").readOne(id)
      console.log("tour Edited Successfully :) ==", tour);
      setEventTourEditData(tour)
      setEventType(tour.event_mode)
      setDescription(tour.description)
      setOtherType(tour.tour_type)
      const slot = toursData.filter((f) => f.tour.id === id)
      const updatedMapPin = `http://maps.google.com?z=12&t=m&q=@${tour?.location?.coordinates[1]},${tour?.location?.coordinates[0]}`;
      setGoogleMapPin(updatedMapPin)
      const uniqueSlotIds = new Set();
      const uniqueData = slot.filter(item => {
        if (!uniqueSlotIds.has(item.slot.id)) {
          uniqueSlotIds.add(item.slot.id);
          return true;
        }
        return false;
      });
      setSlotsDetails(uniqueData)
      setType("tour")
      if (slot.length > 0) setIsSaveBtn(false)
      // return
    }
    setEditOpen(true);
  };

  useEffect(() => {
    if (Lat !== undefined && Lng !== undefined) {
      const updatedMapPin = `http://maps.google.com?z=12&t=m&q=@${Lat},${Lng}`;
      setGoogleMapPin(updatedMapPin);
    }
  }, [Lat, Lng]);


  useEffect(() => {
    try {
      directus
        .items("schools")
        .readByQuery({
          filter: { id: { _eq: schoolId ?? userData.school } },
          // filter: { id: { _eq: userData.school } },
          fields: ["*", "school_calculated_fields.*", "application_extra_requirements.*",],
          meta: ["total_count", "filter_count"],
          sort: ["-is_partner"],
        })
        .then((res) => {
          setSchools(res.data);
        })
        .catch((e) => { console.log("error ==>", e); });
      setSlotInitialValue({
        slotName: "",
        slotStartDate: "",
        slotEndDate: "",
        slotStartTime: "",
        slotEndTime: "",
        id: ""
      })
      const dateTemp = new Date();
      const monthName = dateTemp.toLocaleString('default', { month: 'long' });
      const fullYear = dateTemp.getFullYear()
      setCalenderHeader(`${monthName} ${fullYear}`)

      const fetchData = async () => {
        let filtr, eventFilter, tourFilter ,slotFilter , fields ,eventTable
        const tempDate = new Date(currDate)
        const monthYear = `${tempDate.getMonth() + 1}-${tempDate.getFullYear()}`

        // if (userData.role.name === "Parent") {
        if (schoolId) {
          filtr = { school: { _eq: schoolId }, status: { _neq: "archived" }, month: { _eq: new Date().getMonth() + 1 }, year: { _eq: new Date().getFullYear() } }
          eventFilter = { school: { _eq: schoolId }, status: { _neq: "archived" } }
          tourFilter = { school: { _eq: schoolId }, status: { _neq: "archived" } }
        }
        else {
          filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: new Date().getMonth() + 1 }, year: { _eq: new Date().getFullYear() } }
          eventFilter = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" } }
          tourFilter = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" } }
        }
        if (schoolId) {
          slotFilter = { tour: { school: { _eq: schoolId }, }, month_years: { _contains: monthYear }, status: { _eq: "Draft" } }
          filtr = { school: { _eq: schoolId }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
        } else {
          slotFilter = { tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school } }, month_years: { _contains: monthYear }, status: { _eq: "Draft" } }
          filtr = { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }, status: { _neq: "archived" }, month: { _eq: tempDate.getMonth() + 1 }, year: { _eq: tempDate.getFullYear() } }
        }
        const events_all_data = await directus.items("events").readByQuery({ filter: eventFilter });
        const tours_all_data = await directus.items("tours").readByQuery({ filter: tourFilter });
        const events = await directus.items("events").readByQuery({ filter: filtr, sort: ['-event_date'] })
        eventFilter = { _and: [{ tour: { school: { _eq: paramsData?.schoolid ? paramsData?.schoolid : userData?.school }} },{ slot :{month_years: { _contains: monthYear }}},{ status: { _eq: "Draft" } }] };
        eventTable = "tour_events";
        fields = ["*", "tour.school.*", "slot.*", "tour.*"];
        const tours = await callReadQueryApi(eventTable, eventFilter, fields, ['tour_date'], -1)
        const filteredSlot = tours?.filter((ele) => { 
          const apiMonth = moment(ele?.tour_date).month() + 1 
          const apiYear = moment(ele?.tour_date).year()  
          return tempDate.getMonth()+1 === apiMonth && tempDate.getFullYear() === apiYear
        })
        console.log("filteredSlot..",filteredSlot);
        if ((events_all_data?.data?.length > 0 || filteredSlot?.length > 0) || userRole === 'School Admin') {
          setEtAllData(true)
        } else {
          setEtAllData(false)
        }
        setToursData(filteredSlot)
      }
      fetchData()
    }
    catch (e) {
      console.log('errorzczxc ==>', e)
    }
  }, [])

  return (
    <>
      {authenticated && ( <>
        <LoginModal open={authenticated} openLoginModal={setAuthenticated}className="btn-sign-in homepage-signin" placeholder="Sign In" />
        {/* <RegisterModal className="homepage-signup" /> */}
      </> )
  }
    <div
      className={`grid grid-cols-12 lg:ml-16 gridMargin ${!isMobile && 'res-width'}`}
      style={{ marginTop: "30px", marginRight: !isMobile ? '64px' : '0px' }}
    >
      <ApplySuccessFully
        cancelLabel="Okay"
        message={cancelTour ? "You have cancelled this tour" : "You are already joined!"}
        handleBtn={setJoinConfirmModel}
        openModal={joinConfirmModel ? true : false}
      />

      {confirmModel && (
        <ConfirmDelete
          confirmLabel={cinfirmLbl}
          cancelLabel={cancelLbl}
          message={modalMeassage}
          className="modal video-cinfirm-model"
          image="/images/application-success.png"
          recordId={eventTourEditData?.id}
          type={Type}
          CancelBtnStyle={{ width: "224px", height: "auto" ,paddingTop:'6px' ,paddingBottom:'6px'}}
          ConfirmBtnStyle={{ width: "51%", height: "auto"  ,paddingTop:'6px' ,paddingBottom:'6px' }}
          model={"event-tour"}
          openModal={true}
          handleConfirmClick={confirmClick}
          setConfirmModel={setConfirmModel}
        />
      )}
      {isMobile && <div
        className="grid lg:grid-cols-1 md:grid-cols-2 sm:grid-cols-1 tabletGrid"
        style={{ width: "32%", marginBottom: "20px" }}
      >
        <div
          className="Frame11948 h-94 relative bg-slate-100 rounded-lg"
          style={{ width: "max-content", height: "300px", border: "1px solid #dae2ec", background: "white", paddingBottom: "5px" }}>
          {/* <div className="Frame11946 self-stretch left-[9px] absolute justify-between items-center inline-flex items-baseline mt-2 items-end inline-flex ml-1" >
                    <Tabs>
                      <TabList className="text-lg font-bold  text-gray-900 xborder-b-3 mb-5 mt-0 tablistMobile">
                        <Tab
                          key={"event.id"}
                          onClick={(e) => {
                            handleTabChange("event")
                            setCurrTab("event");
                            setCurrTabName("Event");
                          }}
                        >
                          <div className="flex items-center">
                            <p className="childName">Events</p>
                          </div>
                        </Tab>
                        <Tab
                          key={"tour.id"}
                          onClick={(e) => {
                            handleTabChange("tour")
                            setCurrTab("tour");
                            setCurrTabName("Tour");
                          }}
                        >
                          <div className="flex items-center">
                            <p className="childName">Tours</p>
                          </div>
                        </Tab>
                        <div className="app-border"></div>
                      </TabList>
                    </Tabs>
                    <div className="Frame11947 justify-start items-center gap-2.5 flex res-new1-width" style={{ position: "relative" }}>
                      <button onClick={(e) => handleBackClick(e)}>
                        <ChevronLeftIcon />
                      </button >
                      <p>{calanderHeder}</p>
                      <button onClick={(e) => { handleNextMonthClick(e) }}>
                        <NavigateNextIcon />
                      </button>
                    </div>
                  </div> */}
          <div className="flex justify-between items-center mx-4">
            <div className="Tabs">
              <Tabs>
                <TabList className="text-lg font-bold  text-gray-900 xborder-b-3 mt-0 tablistMobiles">
                <Tab
                    key={"tour.id"}
                    onClick={(e) => {
                      handleTabChange("tour")
                      setCurrTab("tour");
                      setCurrTabName("Tour");
                    }}
                  >
                    <div className="flex items-center">
                      <p className="childName">Tours</p>
                    </div>
                  </Tab>
                  <Tab
                    key={"event.id"}
                    onClick={(e) => {
                      handleTabChange("event")
                      setCurrTab("event");
                      setCurrTabName("Event");
                    }}
                  >
                    <div className="flex items-center">
                      <p className="childName">Events</p>
                    </div>
                  </Tab>
                  <div className="app-border"></div>
                </TabList>
              </Tabs>
            </div>

            <div className="Frame11947 flex items-center gap-2.5 res-new1-width">
              <button onClick={(e) => handleBackClick(e)} disabled={!isButtonEnabled}>
                <ChevronLeftIcon />
              </button>
              <p>{calanderHeder}</p>
              <button onClick={(e) => handleNextMonthClick(e)}>
                <NavigateNextIcon />
              </button>
            </div>
          </div>

          <div className="Line289 self-stretch h-px border border-slate-200 top-[1px] relative"></div>
          <div className="Frame11937 p-3 left-[9px] absolute overflow-y-scroll bg-white rounded-lg flex-col justify-start items-end inline-flex"
            style={{ width: "97%", height: "12rem" }}>
            {/* Event View */}
          {currTabName === "Event" &&
            eventsData?.map((event) => {
              const eventDate = new Date(event?.event_date);
              const eventDateWithoutTime = new Date(
                eventDate.getFullYear(),
                eventDate.getMonth(),
                eventDate.getDate()
              );
              const currentDate = new Date();
              let currentDateWithoutTime = new Date(
                currentDate.getFullYear(),
                currentDate.getMonth(),
                currentDate.getDate()
              );

              const matchDate = eventDateWithoutTime >= currentDateWithoutTime;
              return (
                <>
                  <div key={event.id} className="Frame11942 self-stretch justify-start items-center gap-2.5 inline-flex">
                    <div className="Frame11944 w-6 flex-col justify-start items-center inline-flex">
                      <div className=" text-center text-indigo-950 text-opacity-50 text-xs font-semibold font-['Poppins-Regular']">
                        {new Date(event.event_date).getDate()}
                      </div>
                      <div className="Fri text-center text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                        {getDayString(event.event_date)}
                      </div>
                    </div>
                    <div className="Frame11942 w-3.5 h-3.5 relative">
                      <div className="Ellipse474 w-2 h-2 left-[3px] top-[3px] absolute bg-white rounded-full border border-slate-300" style={{ top: "-7px" }} />
                      <div className="Line291 h-0 overflow-scroll left-[62px] absolute origin-top-left rotate-90 border border-slate-200" style={{ top: "0px", left: "8px", width: "50px" }}></div>

                    </div>
                    <div className="flex justify-between w-full">
                      <div
                        onClick={() => {
                          setShowEventTourData(!showEventTourData)
                          setHoveredItemId(event.id)
                          EventMethod(event.id)
                        }}
                        // onMouseEnter={() => handleMouseEnter(event.id)}
                        onMouseLeave={handleMouseLeave}
                        className="Frame11936 w-48 p-2.5 bg-white rounded-lg flex-col justify-start items-start gap-0.5 inline-flex"
                        style={{ cursor: "pointer" }}
                      >
                        <div id="name1" className="EventName1 text-slate-900 text-xs font-semibold font-['Poppins-Regular']">
                          {event.name}
                        </div>
                        <div className="Pm1AmEventPlace text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                          {`${convertTimeTo12HourFormat(event?.event_start_time)} - ${convertTimeTo12HourFormat(event.event_end_time)}`}
                        </div>
                      </div>
                      {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id  : '')) ? true  : false) && userData?.role.name === "School Admin" && directus.auth.token && userData && <img
                        src="/images/edit.svg"
                        onClick={() => handleEditEvent(event.id, "events")}
                        alt="edit"
                        style={{ cursor: "pointer" }}
                      />}

                    </div>
                  </div >
                  {hoveredItemId === event.id && (
                    <div className="popup flex justify-center" id="popupEventModal" style={{ width: "92%" }}
                      onMouseEnter={() => handleMouseEnter(event.id)}
                    //  onMouseLeave={handleMouseLeave}
                    >
                      <div
                        className="Events h-96 overflow-auto ml-3 mb-5 p-4 bg-white rounded-2xl shadow flex-col justify-start items-start gap-3.5 inline-flex"
                        style={{ width: "97%", height: "auto", border: "1px solid #dae2ec" }}
                      >
                         <div
                            style={{
                              position: "relative",
                              width: "100%",
                              height: "200px",
                            }}
                          >
                            <img
                              className="2022031101442 h-26 rounded-2xl"
                              style={{
                                width: "100%",
                                height: "200px",
                              }}
                              src={`https://stagingcms.edways.com/assets/${event.banner}`}
                            />
                            {(!matchDate ||
                              event?.fully_booked ||
                              EventMemberValid) && (
                              <div
                                style={{
                                  background:
                                    "linear-gradient(0deg, rgba(104, 39, 39, 0.60) 0%, rgba(104, 39, 39, 0.60) 100%)",
                                  position: "absolute",
                                  top: "50%",
                                  left: "50%",
                                  width: "100%",
                                  height: "200px",
                                  transform: "translate(-50%, -50%)",
                                  color: "white",
                                  fontSize: "17px",
                                  fontWeight: "bold",
                                  textAlign: "center",
                                  display: "flex",
                                  flexDirection: "column",
                                  justifyContent: "center",
                                  alignItems: "center",
                                  borderRadius: 15,
                                }}
                              >
                                {!matchDate
                                  ? "This event has already passed."
                                  : event?.fully_booked
                                  ? "Event has been fully booked."
                                  : EventMemberValid
                                  ? "You have already joined this event."
                                  : ""}
                              </div>
                            )}
                          </div>

                        <div className="flex Frame11967 h-8 relative flex justify-end" style={{ width: "97%" }}>
                          <div className="left-0 absolute text-slate-900 text-3xl mr-2 font-bold font-['Poppins-Regular']">
                            {/* {new Date(event.event_date).getDate()} */}
                            {String(new Date(event.event_date).getDate()).padStart(2, '0')}
                          </div>
                          <div className="January2022 left-[23px] top-[14px] ml-5 absolute text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                            {new Date(event.event_date).toLocaleString('en-us', { month: 'long' })}
                            {"  "}{new Date(event.event_date).getFullYear()}
                          </div>
                          <div className="mr-5">
                            <img
                              className="Ellipse475 w-8 h-8 top-0 absolute rounded-full border border-slate-200"
                              src={schools[0].logo != null
                                ? process.env.NEXT_PUBLIC_DIRECTUS_URL + "/assets/" + schools[0].logo
                                : "/images/schoolForm.svg"}
                            />
                          </div>
                        </div>
                        <div className="Frame11966 self-stretch h-10 mt-1 flex-col justify-start items-start gap-1 flex">
                          <div className="EventName2 text-slate-900 text-base font-semibold font-['Poppins-Regular'] eventNameOnClick">
                            {event.name}
                          </div>
                          <div className="Frame12480 self-stretch justify-between items-start inline-flex" style={{ width: "97%" }}>
                            <div className="30Pm1030Pm text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3" style={{ width: "78%" }}>
                              {`${convertTimeTo12HourFormat(event?.event_start_time)} - ${convertTimeTo12HourFormat(event.event_end_time)}`}
                            </div>
                            <div className="OnCampus text-slate-900 text-xs font-normal font-['Poppins-Regular'] leading-3">
                              {event.event_mode}
                            </div>
                          </div>
                        </div>
                        {event?.event_mode !== 'ONLINE' &&
                          <>
                            <div className="Frame11965 flex-col justify-start items-start gap-1 mt-2 flex">
                              <div className="EventPlace text-slate-900 text-xs font-semibold font-['Poppins-Regular'] ">
                                {currTabName} Place
                              </div>
                              <div className="ThArrParis text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                {event.address}
                              </div>
                            </div>
                            <div className="Group10 w-52 h-auto relative" style={{ width: "100%" }}>
                            <GoogleMapMobile
                              mapVisible={true}
                              setMapVisible={true}
                              schools={schools}
                              setMultiView={"event_and_tour_view"}
                              setSchoolLocation={setSchoolLocation}
                              setLat={setLat}
                              setLng={setLng}
                              event_location={event.location}
                            />
                            </div>
                          </>}
                        <div
                          className="Frame11968 flex-col justify-start items-start gap-1 flex"
                          style={{ marginTop: event?.event_mode == 'ONLINE' ? "0px" : "180px", width: "100%" }}
                        >
                          <div className="Description text-slate-900 text-xs font-semibold font-['Poppins-Regular'] pt-2">
                            Description
                          </div>
                          <div
                            className="SedUtPerspiciatisUndeOmnisIsteNatusErrorSitVoluptatemAccusantiumDoloremqueLaudantiumTotamRemAperiamEaqueIpsaQuaeAbIlloInventoreVeritatisEtQuasiArchitectoBeataeVitaeDictaSuntExplicabo text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] leading-3"
                            style={{ width: "100%" }}
                          >
                            {event.description}
                          </div>
                        </div>

                        {userData?.role?.name !== "School Admin" && (
                          <>
                            <ReactTooltip
                              id="tourtip"
                              className="inviteuser-tour-tooltip eventFullyBooked"
                              place="bottom"
                              globalEventOff="click"
                            />
                            {loading  ? <div className="align-middle w-2/5 ixnline-flex items-center border popup-btn cancel" style={{ top: '10%', left: '45%',width: "51%", height: "auto" }}>
                              <div className="spinner-container-login">
                                <div className="loading-spinner-login"></div>
                              </div>
                            </div> :(<div
                              onClick={() => {
                                !event?.fully_booked &&
                                  matchDate &&
                                  joinEventAndTour(event.id, "event");
                              }}
                              className={`ButtonsSecondaryNormal cursor-pointer self-stretch h-10 px-2.5 py-1 origin-center -rotate-180 rounded-2xl border border-red-400 flex-col justify-center items-center flex ${
                                !matchDate ||
                                event?.fully_booked ||
                                EventMemberValid
                                  ? "opacity-50"
                                  : ""
                              }`}
                              data-tip={
                                !matchDate
                                  ? "This event has already passed."
                                  : event?.fully_booked
                                  ? "Event has been fully booked."
                                  : EventMemberValid
                                  ? "You have already joined this event."
                                  : ""
                              }
                              data-for="tourtip"
                            >
                              <div className="Apply cursor-pointer origin-center rotate-180 text-red-400 text-sm font-semibold font-['Poppins-Regular']">
                                {currTabName === "Event"
                                  ? "Join"
                                  : "Book A Tour"}
                              </div>
                            </div>)}
                          </>
                        )}
                      </div>
                    </div>
                  )}
                </>
              );
            })}
            {/* Tour View */}
            {currTabName === "Tour" && toursData?.map((slot) => {
              const currentDate = new Date();
              const dateObject = new Date(currentDate);
              const year = dateObject.getFullYear();
              const month = String(dateObject.getMonth() + 1).padStart(2, '0'); // Months are zero-based
              const day = String(dateObject.getDate()).padStart(2, '0');
              const tour_curr_date = `${year}-${month}-${day}`;

              const slotdateObject = new Date(slot.tour_event_end_date_time);
              const years = slotdateObject.getFullYear();
              const months = String(slotdateObject.getMonth() + 1).padStart(2, '0'); // Months are zero-based
              const days = String(slotdateObject.getDate()).padStart(2, '0');
              const tour_start_date = `${years}-${months}-${days}`;
              const matchTourDate = tour_start_date >= tour_curr_date;
              return (
                <>
                  <div key={slot?.slot?.id} className="Frame11942 self-stretch justify-start items-center gap-2.5 inline-flex">
                    <div className="Frame11944 w-6 flex-col justify-start items-center inline-flex">
                      <div className=" text-center text-indigo-950 text-opacity-50 text-xs font-semibold font-['Poppins-Regular']">
                        {new Date(slot?.tour_date).getDate()}
                      </div>
                      <div className="Fri text-center text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                        {getDayString(slot?.tour_date)}
                      </div>
                    </div>
                    <div className="Frame11942 w-3.5 h-3.5 relative">
                      <div className="Ellipse474 w-2 h-2 left-[3px] top-[3px] absolute bg-white rounded-full border border-slate-300" style={{ top: "-7px" }} />
                      <div className="Line291 h-0 overflow-scroll left-[62px] absolute origin-top-left rotate-90 border border-slate-200" style={{ top: "0px", left: "8px", width: "50px" }}></div>

                    </div>
                    <div className="flex justify-between w-full">
                      <div
                        onClick={() => {
                          setShowEventTourData(!showEventTourData)
                          setHoveredItemId(slot?.id)
                           oneTourMethod(slot?.id)
                      }
                        }
                        // onMouseEnter={() => handleMouseEnter(slot.id)}
                        onMouseLeave={handleMouseLeave}
                        className="Frame11936 w-90 p-2.5 bg-white rounded-lg flex-col justify-start items-start gap-0.5 inline-flex"
                        style={{ cursor: "pointer" }}
                      >
                        <div id="name1" className="EventName1 text-slate-900 text-xs font-semibold font-['Poppins-Regular'] w-90">
                          {slot?.slot?.name}
                        </div>
                        <div className="Pm1AmEventPlace text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                          {`${convertTimeTo12HourFormat(slot?.slot?.slot_start_time)} - ${convertTimeTo12HourFormat(slot?.slot?.slot_end_time)}`}
                        </div>
                      </div>
                      {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id : '')) ? true  : false) && userData?.role.name === "School Admin" && directus.auth.token && userData && <img
                        src="/images/edit.svg"
                        onClick={() => handleEditEvent(slot?.tour?.id, "tours")}
                        alt="edit"
                        style={{ cursor: "pointer" }}
                      />}

                    </div>
                  </div>
                  {hoveredItemId === slot?.id && (
                    <div className="popup flex justify-center" id="popupEventModal" style={{ width: "92%" }}
                    onMouseEnter={() => handleMouseEnter(slot?.id)}
                      onMouseLeave={handleMouseLeave}
                    // onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)}
                    >
                      <div
                        className="Events h-96 overflow-auto ml-3 p-4 bg-white rounded-2xl shadow flex-col justify-start items-start gap-3.5 inline-flex"
                        style={{ width: "97%", height: "auto", border: "1px solid #dae2ec" }}
                      >
                        <div className="Frame11967 w-52 h-8 relative flex justify-end" style={{ width: "97%" }}>
                          <div className="left-0 absolute text-slate-900 text-3xl mr-2 font-bold font-['Poppins-Regular']">
                          {String(new Date(slot?.tour_date).getDate()).padStart(2, '0')}
                          </div>
                          <div className="January2022 left-[23px] top-[14px] ml-5 absolute text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                          {new Date(slot?.tour_date).toLocaleString("en-us", {
                              month: "long",
                            })}
                            {"  "} {new Date(slot?.tour_date).getFullYear()}
                          </div>
                          <div className="mr-5">
                            <img
                              className="Ellipse475 w-8 h-8 top-0 absolute rounded-full border border-slate-200"
                              src={schools[0].logo != null
                                ? process.env.NEXT_PUBLIC_DIRECTUS_URL + "/assets/" + schools[0].logo
                                : "/images/schoolForm.svg"}
                            />
                          </div>
                        </div>
                        <div className="Frame11966 self-stretch h-10 mt-0 flex-col justify-start items-start gap-1 flex">
                          <div className="EventName2 text-slate-900 text-base font-semibold font-['Poppins-Regular'] eventNameOnClick">
                            {slot?.slot?.name}
                          </div>
                          <div className="Frame12480 self-stretch justify-between items-start inline-flex">
                            <div className="30Pm1030Pm text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3" style={{ width: "78%" }}>
                              {`${convertTimeTo12HourFormat(slot?.slot?.slot_start_time)} - ${convertTimeTo12HourFormat(slot.slot.slot_end_time)}`}
                            </div>
                            <div className="OnCampus text-slate-900 text-xs font-normal font-['Poppins-Regular'] leading-3">
                              {slot?.tour?.event_mode}
                            </div>
                          </div>
                        </div>
                        {slot?.tour?.event_mode !== "ONLINE" && (
                          <>
                            <div className="Frame11965 flex-col justify-start items-start gap-1 flex mt-1">
                              <div className="EventPlace text-slate-900 text-xs font-semibold font-['Poppins-Regular']">
                                {currTabName} Place
                              </div>
                              <div className="ThArrParis text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                {slot?.tour?.address}
                              </div>
                            </div>
                            <div
                              className="Group10 w-52 h-auto relative"
                              style={{ width: "100%" }}
                            >
                              <GoogleMapMobile
                            mapVisible={true}
                            setMapVisible={true}
                            schools={schools}
                            setMultiView={"event_and_tour_view"}
                            setSchoolLocation={setSchoolLocation}
                            setLat={setLat}
                            setLng={setLng}
                            tour_location={slot.tour.location}
                          />
                        </div>
                          </>
                        )}
                        <div
                          className="Frame11968 flex-col justify-start items-start gap-1 flex"
                          style={{
                            marginTop:
                              slot?.tour?.event_mode !== "ONLINE"
                                ? "180px"
                                : undefined,
                            width: "100%",
                          }}

                        >
                          <div className="Description text-slate-900 text-xs font-semibold font-['Poppins-Regular'] pt-2">
                            Description
                          </div>
                          <div
                            className="SedUtPerspiciatisUndeOmnisIsteNatusErrorSitVoluptatemAccusantiumDoloremqueLaudantiumTotamRemAperiamEaqueIpsaQuaeAbIlloInventoreVeritatisEtQuasiArchitectoBeataeVitaeDictaSuntExplicabo text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] leading-3"
                            style={{ width: "100%" }}
                          >
                            {slot?.tour?.description}
                          </div>
                        </div>

                        {userData?.role?.name !== "School Admin" && (
                          <>
                            <ReactTooltip
                              id="tourtip2"
                              className="inviteuser-tour-tooltip eventFullyBooked"
                              place="bottom"
                              globalEventOff="click"
                            />
                            {loading ? <div className="align-middle w-full ixnline-flex items-center border popup-btn cancel" style={{ top: '10%', left: '45%', height: "auto" }}>
                              <div className="spinner-container-login">
                                <div className="loading-spinner-login"></div>
                              </div>
                            </div> : (<div
                              onClick={() => {
                                matchTourDate &&
                                  !slot?.fully_booked_tour_event &&
                                  !tourEventMemberValid &&
                                  joinEventAndTour(slot?.id, "tour");
                              }}
                              className={`ButtonsSecondaryNormal cursor-pointer self-stretch h-10 px-2.5 py-1 origin-center -rotate-180 rounded-2xl border border-red-400 flex-col justify-center items-center flex ${slot?.fully_booked_tour_event ||
                                  tourEventMemberValid ||
                                  !matchTourDate
                                  ? "opacity-20"
                                  : ""
                                }`}
                              data-tip={
                                !matchTourDate
                                  ? "This slot has already passed."
                                  : slot?.fully_booked_tour_event
                                    ? "Slot has been fully Booked."
                                    : tourEventMemberValid
                                      ? "You have already joined this tour."
                                      : ""
                              }
                              data-for="tourtip2"
                            >
                              <div className="Apply cursor-pointer origin-center rotate-180 text-red-400 text-sm font-semibold font-['Poppins-Regular']">
                                {currTabName === "Event"
                                  ? "Join"
                                  : "Book A Tour"}{" "}
                              </div>
                            </div>)}
                          </>
                        )}
                      </div>
                    </div>
                  )}
                </>
              )
            })}
          </div>
          <div className="Plus-Add-Button float-right mb-2" style={{ marginLeft: "auto", marginTop: "189px", marginRight: "5%" }}>
            {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id : '')) ? true  : false) && userData?.role.name === "School Admin" && directus.auth.token && userData &&
              <div
                onClick={handleAddEvent}
                className="ButtonsRoundedButtonNormal w-10 h-10 p-2 -rotate-180 bg-red-400 rounded-3xl shadow flex-col justify-center items-center gap-4 inline-flex"
                style={{ cursor: "pointer", marginTop: "15%", padding: "14px" }}>
                <img src="/images/PlusWhite.png" />
              </div>
            }
          </div>
        </div>
      </div>}
      <div className="col-span-12">
        <Tabs  defaultIndex={0}>
          <TabList id="tabList">
            <Tab className="react-tabs__tab tab-name">Academic</Tab>
            <Tab className="react-tabs__tab tab-name">Admissions</Tab>
            <Tab className="react-tabs__tab tab-name">School</Tab>
          </TabList>
          <TabPanel>
            <div className={etAllData ? "flex" : ""}>
              <div
                className={etAllData ? "grid lg:grid-cols-2 md:grid-cols-2 sm:grid-cols-1 tabletGrid" : "grid lg:grid-cols-3 md:grid-cols-2 sm:grid-cols-1 tabletGrid"}
                style={{ width: etAllData && !isMobile ? "68%" : "" }}
              >
                {attributes
                  .filter(function (attribute) {
                    return (
                      attribute.category == "Academic" && attribute.order >= 0
                    );
                  })
                  .sort((a, b) => parseInt(a.order) - parseInt(b.order))
                  .map((attr) => {
                    const values = schoolِAttributes.filter(function (value) {
                      return value.attribute == attr.id;
                    });
                    if (values.length > 0) {
                      return (
                        <SchoolAttributeCard
                          key={attr.id}
                          attr={attr}
                          values={values}
                        />
                      );
                    }
                  })}
              </div>
              {etAllData && !isMobile && <div className="grid lg:grid-cols-1 md:grid-cols-2 sm:grid-cols-1 tabletGrid" style={{ width: "32%" }}>
                <div className="Frame11948 h-94 relative bg-slate-100 rounded-lg"
                  style={{ width: "100%", height: "100%", border: "1px solid #dae2ec", background: "white", paddingBottom: "5px" }}>
                  {/* <div className="Frame11946 self-stretch left-[9px] absolute justify-between items-center inline-flex items-baseline mt-2 items-end inline-flex ml-1" >
                    <Tabs>
                      <TabList className="text-lg font-bold  text-gray-900 xborder-b-3 mb-5 mt-0 tablistMobile">
                        <Tab
                          key={"event.id"}
                          onClick={(e) => {
                            handleTabChange("event")
                            setCurrTab("event");
                            setCurrTabName("Event");
                          }}
                        >
                          <div className="flex items-center">
                            <p className="childName">Events</p>
                          </div>
                        </Tab>
                        <Tab
                          key={"tour.id"}
                          onClick={(e) => {
                            handleTabChange("tour")
                            setCurrTab("tour");
                            setCurrTabName("Tour");
                          }}
                        >
                          <div className="flex items-center">
                            <p className="childName">Tours</p>
                          </div>
                        </Tab>
                        <div className="app-border"></div>
                      </TabList>
                    </Tabs>
                    <div className="Frame11947 justify-start items-center gap-2.5 flex res-new1-width" style={{ position: "relative" }}>
                      <button onClick={(e) => handleBackClick(e)}>
                        <ChevronLeftIcon />
                      </button >
                      <p>{calanderHeder}</p>
                      <button onClick={(e) => { handleNextMonthClick(e) }}>
                        <NavigateNextIcon />
                      </button>
                    </div>
                  </div> */}
                  <div className="flex justify-between items-center m-4">
                    <div className="Tabs">
                      <Tabs defaultIndex={0}>
                        <TabList className="text-lg font-bold  text-gray-900 xborder-b-3 mt-0 tablistMobile">
                          <Tab
                            key={"tour.id"}
                            onClick={(e) => {
                              handleTabChange("tour")
                              setCurrTab("tour");
                              setCurrTabName("Tour");
                            }}
                          >
                            <div className="flex items-center">
                              <p className="childName">Tours</p>
                            </div>
                          </Tab>
                          <Tab
                            key={"event.id"}
                            onClick={(e) => {
                              handleTabChange("event")
                              setCurrTab("event");
                              setCurrTabName("Event");
                            }}
                          >
                            <div className="flex items-center">
                              <p className="childName">Events</p>
                            </div>
                          </Tab>
                          <div className="app-border"></div>
                        </TabList>
                      </Tabs>
                    </div>

                    <div className="Frame11947 flex items-center gap-2.5 res-new1-width">
                      <button onClick={(e) => handleBackClick(e)} disabled={!isButtonEnabled}>
                        <ChevronLeftIcon />
                      </button>
                      <p>{calanderHeder}</p>
                      <button onClick={(e) => handleNextMonthClick(e)}>
                        <NavigateNextIcon />
                      </button>
                    </div>
                  </div>

                  <div className="Line289 self-stretch h-px border border-slate-200 top-[1px] relative"></div>
                  <div className="Frame11937 p-3 left-[9px] absolute overflow-y-scroll bg-white rounded-lg flex-col justify-start items-end inline-flex"
                    style={{ width: "98%", height: "22.5rem" }}>
                    {/* Event View */}
                    {currTabName === "Event" && eventsData?.map((event) => {
                      const eventDate = new Date(event?.event_date);
                      const eventDateWithoutTime = new Date(
                        eventDate.getFullYear(),
                        eventDate.getMonth(),
                        eventDate.getDate()
                      );
                      const currentDate = new Date();
                      let currentDateWithoutTime = new Date(
                        currentDate.getFullYear(),
                        currentDate.getMonth(),
                        currentDate.getDate()
                      );

                      const matchDate = eventDateWithoutTime >= currentDateWithoutTime;
                      return (
                        <>
                          <div key={event.id} className="Frame11942 self-stretch justify-start items-center gap-2.5 inline-flex">
                            <div className="Frame11944 w-6 flex-col justify-start items-center inline-flex">
                              <div className=" text-center text-indigo-950 text-opacity-50 text-xs font-semibold font-['Poppins-Regular']">
                                {new Date(event.event_date).getDate()}
                              </div>
                              <div className="Fri text-center text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                {getDayString(event.event_date)}
                              </div>
                            </div>
                            <div className="Frame11942 w-3.5 h-3.5 relative">
                              <div className="Ellipse474 w-2 h-2 left-[3px] top-[3px] absolute bg-white rounded-full border border-slate-300" style={{ top: "-7px" }} />
                              <div className="Line291 h-0 overflow-scroll left-[62px] absolute origin-top-left rotate-90 border border-slate-200" style={{ top: "0px", left: "8px", width: "50px" }}></div>

                            </div>
                            <div className="flex justify-between w-full">
                              <div
                                onClick={() => {
                                  setShowEventTourData(!showEventTourData)
                                  setHoveredItemId(event.id)
                                  EventMethod(event.id)
                                }}
                                // onMouseEnter={() => handleMouseEnter(event.id)}
                                onMouseLeave={handleMouseLeave}
                                className="Frame11936 w-48 p-2.5 bg-white rounded-lg flex-col justify-start items-start gap-0.5 inline-flex"
                                style={{ cursor: "pointer" }}
                              >
                                <div id="name1" className="EventName1 text-slate-900 text-xs font-semibold font-['Poppins-Regular']">
                                  {event.name}
                                </div>
                                <div className="Pm1AmEventPlace text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                  {`${convertTimeTo12HourFormat(event?.event_start_time)} - ${convertTimeTo12HourFormat(event.event_end_time)}`}
                                </div>
                              </div>
                              {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id : '')) ? true  : false)  && userData?.role.name === "School Admin"  && directus.auth.token && userData && <img
                                src="/images/edit.svg"
                                onClick={() => handleEditEvent(event.id, "events")}
                                alt="edit"
                                style={{ cursor: "pointer" }}
                              />}

                            </div>
                          </div >
                          {hoveredItemId === event.id && (
                            <div className="popup flex justify-center" id="popupEventModal" style={{ width: "92%" }}
                              onMouseEnter={() => handleMouseEnter(event.id)}
                            //  onMouseLeave={handleMouseLeave}
                            >
                              <div
                                className="Events h-96 overflow-auto ml-3 mb-5 p-4 bg-white rounded-2xl shadow flex-col justify-start items-start gap-3.5 inline-flex"
                                style={{ width: "97%", height: "auto", border: "1px solid #dae2ec" }}
                              >
                                {event.banner && (
                                  <div style={{ position: 'relative', width: '100%', height: '200px', }}>
                                    <img
                                      className="2022031101442 h-26 rounded-2xl"
                                      style={{
                                        width: '100%',
                                        height: '200px',
                                      }}
                                      src={`https://stagingcms.edways.com/assets/${event.banner}`}
                                    />
                                    {(!matchDate || event?.fully_booked || EventMemberValid) && (
                                      <div
                                        style={{
                                          background: 'linear-gradient(0deg, rgba(104, 39, 39, 0.60) 0%, rgba(104, 39, 39, 0.60) 100%)',
                                          position: 'absolute',
                                          top: '50%',
                                          left: '50%',
                                          width: '100%',
                                          height: '200px',
                                          transform: 'translate(-50%, -50%)',
                                          color: 'white',
                                          fontSize: '17px',
                                          fontWeight: 'bold',
                                          textAlign: 'center',
                                          display: 'flex',
                                          flexDirection: 'column',
                                          justifyContent: 'center',
                                          alignItems: 'center',
                                          borderRadius: 15
                                        }}
                                      >
                                        {!matchDate ? "This event has already passed." : event?.fully_booked ? "Event has been fully booked." : EventMemberValid ? "You have already joined this event." : ""}
                                      </div>
                                    )}
                                  </div>
                                )}
                                <div className="flex Frame11967 h-8 relative flex justify-end" style={{ width: "97%" }}>
                                  <div className="left-0 absolute text-slate-900 text-3xl mr-2 font-bold font-['Poppins-Regular']">
                                    {String(new Date(event.event_date).getDate()).padStart(2, '0')}
                                  </div>
                                  <div className="January2022 left-[23px] top-[14px] ml-5 absolute text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                    {new Date(event.event_date).toLocaleString('en-us', { month: 'long' })}
                                    {"  "}{new Date(event.event_date).getFullYear()}
                                  </div>
                                  <div className="mr-5">
                                    <img
                                      className="Ellipse475 w-8 h-8 top-0 absolute rounded-full border border-slate-200"
                                      src={schools[0].logo != null
                                        ? process.env.NEXT_PUBLIC_DIRECTUS_URL + "/assets/" + schools[0].logo
                                        : "/images/schoolForm.svg"}
                                    />
                                  </div>
                                </div>
                                <div className="Frame11966 self-stretch h-10 mt-1 flex-col justify-start items-start gap-1 flex">
                                  <div className="EventName2 text-slate-900 text-base font-semibold font-['Poppins-Regular'] eventNameOnClick">
                                    {event.name}
                                  </div>
                                  <div className="Frame12480 self-stretch justify-between items-start inline-flex" style={{ width: "97%" }}>
                                    <div className="30Pm1030Pm text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3" style={{ width: "78%" }}>
                                      {`${convertTimeTo12HourFormat(event?.event_start_time)} - ${convertTimeTo12HourFormat(event.event_end_time)}`}
                                    </div>
                                    <div className="OnCampus text-slate-900 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                      {event.event_mode}
                                    </div>
                                  </div>
                                </div>
                                {event?.event_mode !== 'ONLINE' &&
                                  <>
                                    <div className="Frame11965 flex-col justify-start items-start gap-1 mt-2 flex">
                                      <div className="EventPlace text-slate-900 text-xs font-semibold font-['Poppins-Regular'] ">
                                        {currTabName} Place
                                      </div>
                                      <div className="ThArrParis text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                        {event.address}
                                      </div>
                                    </div>
                                    <div className="Group10 w-52 h-auto relative" style={{ width: "100%" }}>
                                      < GoogleMapWeb
                                        mapVisible={true}
                                        setMapVisible={true}
                                        schools={schools}
                                        setMultiView={"event_and_tour_view"}
                                        setSchoolLocation={setSchoolLocation}
                                        setLat={setLat}
                                        setLng={setLng}
                                        event_location={event.location}
                                      />
                                    </div>
                                  </>}
                                <div
                                  className="Frame11968 flex-col justify-start items-start gap-1 flex"
                                  style={{ marginTop: event?.event_mode == 'ONLINE' ? "0px" : "180px", width: "100%" }}
                                >
                                  <div className="Description text-slate-900 text-xs font-semibold font-['Poppins-Regular'] pt-2">
                                    Description
                                  </div>
                                  <div
                                    className="SedUtPerspiciatisUndeOmnisIsteNatusErrorSitVoluptatemAccusantiumDoloremqueLaudantiumTotamRemAperiamEaqueIpsaQuaeAbIlloInventoreVeritatisEtQuasiArchitectoBeataeVitaeDictaSuntExplicabo text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] leading-3"
                                    style={{ width: "100%" }}
                                  >
                                    {event.description}
                                  </div>
                                </div>
                                {userData?.role?.name !== "School Admin" && (
                                  <>
                                    <ReactTooltip
                                      id="tourtip"
                                      className="inviteuser-tour-tooltip eventFullyBooked"
                                      place="bottom"
                                      globalEventOff="click"
                                    />
                                    {loading ? <div className="align-middle w-full ixnline-flex items-center border popup-btn cancel" style={{ top: '10%', left: '45%', height: "auto" }}>
                                      <div className="spinner-container-login">
                                        <div className="loading-spinner-login"></div>
                                      </div>
                                    </div> : (<div
                                      onClick={() => {
                                        (!event?.fully_booked && matchDate && joinEventAndTour(event.id, "event"));
                                      }}
                                      className={`ButtonsSecondaryNormal cursor-pointer self-stretch h-10 px-2.5 py-1 origin-center -rotate-180 rounded-2xl border border-red-400 flex-col justify-center items-center flex ${! matchDate || event?.fully_booked || EventMemberValid ? 'opacity-50' : ''}` }
                                      data-tip={
                                        !matchDate? "This event has already passed." : event?.fully_booked ? "Event has been fully booked." : EventMemberValid ? "You have already joined this event." : ""
                                    }
                                      data-for="tourtip"
                                    >
                                      <div className="Apply cursor-pointer origin-center rotate-180 text-red-400 text-sm font-semibold font-['Poppins-Regular']">
                                        {currTabName === "Event" ? "Join" : "Book A Tour"}
                                      </div>
                                    </div>)}
                                  </>
                                )}
                              </div>
                            </div>
                          )}
                        </>
                      )
                    })}
                    {/* Tour View */}
                    {currTabName === "Tour" && toursData?.map((slot) => {
                      // Convert String to Date
                      const currentDate = new Date();
                      const dateObject = new Date(currentDate);
                      const year = dateObject.getFullYear();
                      const month = String(dateObject.getMonth() + 1).padStart(2, '0'); // Months are zero-based
                      const day = String(dateObject.getDate()).padStart(2, '0');
                      const tour_curr_date = `${year}-${month}-${day}`;

                      const slotdateObject = new Date(slot.tour_event_end_date_time);
                      const years = slotdateObject.getFullYear();
                      const months = String(slotdateObject.getMonth() + 1).padStart(2, '0'); // Months are zero-based
                      const days = String(slotdateObject.getDate()).padStart(2, '0');
                      const tour_start_date = `${years}-${months}-${days}`;
                      const matchTourDate = tour_start_date >= tour_curr_date;
                      return (
                        <>

                          <div key={slot?.slot?.id} className="Frame11942 self-stretch justify-start items-center gap-2.5 inline-flex">
                            <div className="Frame11944 w-6 flex-col justify-start items-center inline-flex">
                              <div className=" text-center text-indigo-950 text-opacity-50 text-xs font-semibold font-['Poppins-Regular']">
                                {new Date(slot?.tour_date).getDate()}
                              </div>
                              <div className="Fri text-center text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                {getDayString(slot?.tour_date)}
                              </div>
                            </div>
                            <div className="Frame11942 w-3.5 h-3.5 relative">
                              <div className="Ellipse474 w-2 h-2 left-[3px] top-[3px] absolute bg-white rounded-full border border-slate-300" style={{ top: "-7px" }} />
                              <div className="Line291 h-0 overflow-scroll left-[62px] absolute origin-top-left rotate-90 border border-slate-200" style={{ top: "0px", left: "8px", width: "50px" }}></div>

                            </div>
                            <div className="flex justify-between w-full">
                              <div
                                onClick={() => {
                                  setShowEventTourData(!showEventTourData)
                                  setHoveredItemId(slot?.id)
                                  oneTourMethod(slot?.id)
                                }
                                }
                                // onMouseEnter={() => handleMouseEnter(slot.id)}
                                onMouseLeave={handleMouseLeave}
                                className="Frame11936 w-90 p-2.5 bg-white rounded-lg flex-col justify-start items-start gap-0.5 inline-flex"
                                style={{ cursor: "pointer" }}
                              >
                                <div id="name1" className="EventName1 text-slate-900 text-xs font-semibold font-['Poppins-Regular'] w-90">
                                  {slot?.slot?.name}
                                </div>
                                <div className="Pm1AmEventPlace text-indigo-950 text-opacity-50 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                  {`${convertTimeTo12HourFormat(slot?.slot?.slot_start_time)} - ${convertTimeTo12HourFormat(slot?.slot?.slot_end_time)}`}
                                </div>
                              </div>
                              {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id : '')) ? true  : false) && userData?.role.name === "School Admin" && directus.auth.token && userData && <img
                                src="/images/edit.svg"
                                onClick={() => handleEditEvent(slot?.tour?.id, "tours")}
                                alt="edit"
                                style={{ cursor: "pointer" }}
                              />}

                            </div>
                          </div>
                          {hoveredItemId === slot?.id && (
                            <div className="popup flex justify-center" id="popupEventModal" style={{ width: "92%" }}
                              onMouseEnter={() => handleMouseEnter(slot?.id)}
                              onMouseLeave={handleMouseLeave}
                            // onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)}
                            >
                              <div
                                className="Events h-96 overflow-auto ml-3 p-4 bg-white rounded-2xl shadow flex-col justify-start items-start gap-3.5 inline-flex"
                                style={{ width: "97%", height: "auto", border: "1px solid #dae2ec" }}
                              >
                                <div className="Frame11967 w-52 h-8 relative flex justify-end" style={{ width: "97%" }}>
                                  <div className="left-0 absolute text-slate-900 text-3xl mr-2 font-bold font-['Poppins-Regular']">
                                    {/* {new Date(slot?.slot_start_date).getDate()} */}
                                    {String(new Date(slot?.tour_date).getDate()).padStart(2, '0')}
                                  </div>
                                  <div className="January2022 left-[23px] top-[14px] ml-5 absolute text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                    {new Date(slot?.tour_date).toLocaleString('en-us', { month: 'long' })}
                                    {"  "} {new Date(slot?.tour_date).getFullYear()}
                                  </div>
                                  <div className="mr-5">
                                    <img
                                      className="Ellipse475 w-8 h-8 top-0 absolute rounded-full border border-slate-200"
                                      src={schools[0].logo != null
                                        ? process.env.NEXT_PUBLIC_DIRECTUS_URL + "/assets/" + schools[0].logo
                                        : "/images/schoolForm.svg"}
                                    />
                                  </div>
                                </div>
                                <div className="Frame11966 self-stretch h-10 mt-0 flex-col justify-start items-start gap-1 flex">
                                  <div className="EventName2 text-slate-900 text-base font-semibold font-['Poppins-Regular'] eventNameOnClick">
                                    {slot?.slot?.name}
                                  </div>
                                  <div className="Frame12480 self-stretch justify-between items-start inline-flex">
                                    <div className="30Pm1030Pm text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3" style={{ width: "78%" }}>
                                      {`${convertTimeTo12HourFormat(slot?.slot?.slot_start_time)} - ${convertTimeTo12HourFormat(slot.slot.slot_end_time)}`}
                                    </div>
                                    <div className="OnCampus text-slate-900 text-xs font-normal font-['Poppins-Regular'] leading-3">
                                      {slot?.tour?.event_mode}
                                    </div>
                                  </div>
                                </div>
                                {slot?.tour?.event_mode !== "ONLINE" &&
                                  <>
                                    <div className="Frame11965 flex-col justify-start items-start gap-1 flex mt-1">
                                      <div className="EventPlace text-slate-900 text-xs font-semibold font-['Poppins-Regular']">
                                        {currTabName} Place
                                      </div>
                                      <div className="ThArrParis text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] uppercase leading-3">
                                        {slot?.tour?.address}
                                      </div>
                                    </div>
                                    <div className="Group10 w-52 h-auto relative" style={{ width: "100%" }}>
                                      <GoogleMapWeb
                                        mapVisible={true}
                                        setMapVisible={true}
                                        schools={schools}
                                        setMultiView={"event_and_tour_view"}
                                        setSchoolLocation={setSchoolLocation}
                                        setLat={setLat}
                                        setLng={setLng}
                                        tour_location={slot?.tour?.location}
                                      />
                                    </div>
                                  </>}
                                <div
                                  className="Frame11968 flex-col justify-start items-start gap-1 flex"
                                  style={{ marginTop: slot?.tour?.event_mode !== "ONLINE" ? "150px" : undefined, width: "100%" }}
                                >
                                  <div className="Description text-slate-900 text-xs font-semibold font-['Poppins-Regular'] pt-2">
                                    Description
                                  </div>
                                  <div
                                    className="SedUtPerspiciatisUndeOmnisIsteNatusErrorSitVoluptatemAccusantiumDoloremqueLaudantiumTotamRemAperiamEaqueIpsaQuaeAbIlloInventoreVeritatisEtQuasiArchitectoBeataeVitaeDictaSuntExplicabo text-indigo-950 text-opacity-70 text-xs font-normal font-['Poppins-Regular'] leading-3"
                                    style={{ width: "100%" }}
                                  >
                                    {slot?.tour?.description}
                                  </div>
                                </div>
                                {userData?.role?.name !== "School Admin" &&
                                  <>
                                    <ReactTooltip
                                      id="tourtip2"
                                      className="inviteuser-tour-tooltip eventFullyBooked"
                                      place="bottom"
                                      globalEventOff="click"
                                    />
                                  {loading ? <div className="align-middle w-full ixnline-flex items-center border popup-btn cancel" style={{ top: '10%', left: '45%', height: "auto" }}>
                                    <div className="spinner-container-login">
                                      <div className="loading-spinner-login"></div>
                                    </div>
                                  </div> : (<div onClick={() => { matchTourDate && !slot?.fully_booked && !tourEventMemberValid && joinEventAndTour(slot?.id, "tour") }}
                                    className={`ButtonsSecondaryNormal cursor-pointer self-stretch h-10 px-2.5 py-1 origin-center -rotate-180 rounded-2xl border border-red-400 flex-col justify-center items-center flex ${slot?.fully_booked_tour_event || tourEventMemberValid || !matchTourDate ? 'opacity-20' : ''}`}
                                    data-tip={
                                      !matchTourDate
                                        ? "This slot has already passed." :
                                        slot?.fully_booked_tour_event
                                          ? "Slot has been fully Booked."
                                          : (tourEventMemberValid ? "You have already joined this tour." : "")}
                                    data-for="tourtip2">
                                    <div className="Apply cursor-pointer origin-center rotate-180 text-red-400 text-sm font-semibold font-['Poppins-Regular']">
                                      {currTabName === "Event"
                                        ? "Join"
                                        : "Book A Tour"}{" "}
                                    </div>
                                  </div>)}
                                  </>}
                              </div>
                            </div>
                          )}
                        </>
                      )
                    })}
                  </div>
                  <div className="Plus-Add-Button float-right mb-2" style={{ marginLeft: "auto", marginTop: "368px", marginRight: "5%" }}>
                  {userRole !== "Parent" && ((paramsData?.schoolid === String(userData?.school)|| String(userData?.school) === String(schools ? schools[0]?.id : '')) ? true  : false) && userData?.role.name === "School Admin" && directus.auth.token && userData &&
                      <div
                        onClick={handleAddEvent}
                        className="ButtonsRoundedButtonNormal w-10 h-10 p-2 -rotate-180 bg-red-400 rounded-3xl shadow flex-col justify-center items-center gap-4 inline-flex"
                        style={{ cursor: "pointer", marginTop: "15%", padding: "14px" }}>
                        <img src="/images/PlusWhite.png" />
                      </div>
                    }
                  </div>
                </div>
              </div>}
            </div>
          </TabPanel>
          <TabPanel>
            <div className="grid lg:grid-cols-3 md:grid-cols-2 sm:grid-cols-1 tabletGrid">
              {attributes
                .filter(function (attribute) {
                  return (
                    attribute.category == "Admissions" && attribute.order >= 0
                  );
                })
                .sort((a, b) => parseInt(a.order) - parseInt(b.order))
                .map((attr) => {
                  const values = schoolِAttributes.filter(function (value) {
                    return value.attribute == attr.id;
                  });
                  if (values.length > 0) {
                    return (
                      <SchoolAttributeCard
                        key={attr.id}
                        attr={attr}
                        values={values}
                      />
                    );
                  }
                })}
            </div>
          </TabPanel>
          <TabPanel>
            <div className="grid lg:grid-cols-3 md:grid-cols-2 sm:grid-cols-1 tabletGrid">
              {attributes
                .filter(function (attribute) {
                  return attribute.category == "School" && attribute.order >= 0;
                })
                .sort((a, b) => parseInt(a.order) - parseInt(b.order))
                .map((attr) => {
                  const values = schoolِAttributes.filter(function (value) {
                    return value.attribute == attr.id;
                  });
                  if (values.length > 0) {
                    return (
                      <SchoolAttributeCard
                        key={attr.id}
                        attr={attr}
                        values={values}
                      />
                    );
                  }
                })}
            </div>
          </TabPanel>
        </Tabs>
      </div>
      {/* Add Event and tour Modal */}
      <Transition.Root show={open} as={Fragment}>
        <Dialog as="div" className="relative z-10" onClose={setOpen}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
          </Transition.Child>

            <div className="fixed z-10 inset-0 overflow-y-auto">
              <div className="flex items-end sm:items-center justify-center min-h-full p-4 text-center sm:p-0">
                <Transition.Child
                  as={Fragment}
                  enter="ease-out duration-300"
                  enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                  enterTo="opacity-100 translate-y-0 sm:scale-100"
                  leave="ease-in duration-200"
                  leaveFrom="opacity-100 translate-y-0 sm:scale-100"
                  leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                >
                  <Dialog.Panel
                    className="relative bg-white rounded-lg  text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:max-w-lg sm:w-full sm:p-0"
                    style={{ maxHeight: "55rem", maxWidth: "41rem" }}
                  >
                    <Formik
                      initialValues={{
                        name: "",
                        event_start_time: "",
                        event_end_time: "",
                        event_date: "",
                        address: "",
                        description: "",
                        meeting_url: "",
                        google_map_pin: googleMapPin,
                        event_date: "",
                        weekDay: "",
                        endDate: "",
                        banner: "",
                        slot_name: slotInitialValue?.slotName,
                        slot_start_date: slotInitialValue?.slotStartDate,
                        slot_end_date: slotInitialValue?.slotEndDate,
                        slot_start_time: slotInitialValue?.slotStartTime,
                        slot_end_time: slotInitialValue?.slotEndTime,
                        slot_id: slotInitialValue?.id
                      }}
                      validationSchema={Yup.object().shape({
                      event_start_time: currTab === "event" ? Yup.string().required('Start time is required') : Yup.string(),
                      event_end_time: currTab === "event" ? Yup.string()
                        .required('End time is required')
                        .test(
                          'time-difference',
                          'The difference between start and end time should be at least 30 minutes',
                          function (value) {
                            const { event_start_time } = this.parent;
                            console.log("value..event_start_time...",value ,event_start_time);
                            if (event_start_time && value) {
                              const startTime = new Date(`1970-01-01T${event_start_time}`);
                              const endTime = new Date(`1970-01-01T${value}`);
                              const timeDifference = endTime - startTime;
                              const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                              return timeDifference >= minimumDifference;
                            }
                            return true;
                          }
                        ):Yup.string()
                    })}
                    onSubmit={(values, actions) => {
                        currTab === "event" ?
                          handleEventSubmit(values) :
                          handleTourSubmit(values);
                        return;
                      }}
                    >
                      {(values) => (
                        <Form>
                          <div className="flex flex-row">
                            <div className="w/1-4 edit-event-image">
                              <img
                                className="h-full"
                                src="/images/FrameEventEdit.png"
                                alt="OSS Sign In"
                              />
                            </div>
                            <div
                              className={`flex flex-col ${isMobile ? 'w-full' : 'w-3/4'}  py-1 px-6`}
                              style={{ height: "65rem", marginLeft: `${isMobile ? '0px' : '34px'}` }}
                            >
                              <div className="flex items-center justify-between">
                                <div className="mt-1 ml-1  text-2xl font-extrabold text-gray-900">
                                  Create {currTab === "event" ? "an Event" : "a Tour"}
                                </div>
                                <button
                                  type="button"
                                  className=" text-bold"
                                  onClick={() => {
                                    setOpen(false);
                                  }}
                                >
                                  <XIcon className="w-4 h-4" />
                                </button>
                              </div>
                              <div className="bg-white py-4 pt-0">
                                <div className={`Inputs ${isMobile ? 'w-full' : 'w-96'} h-96 bg-white rounded-lg flex-col justify-start items-start inline-flex`}>
                                  <div className={`Inputs ${isMobile ? 'w-full' : 'w-96'} h-85 bg-white rounded-lg flex-col justify-end items-start inline-flex`}>
                                    <div className={`Section flex-col justify-start items-start gap-2.5 flex ${isMobile ? 'w-full' : ''}`}></div>
                                    <div className={`Section flex-col ${isMobile ? 'w-full' : ''} justify-start  flex`}>
                                      <div className={`Frame12450 ${isMobile ? 'w-full' : 'w-96'} flex-col justify-start gap-5 inline-flex `}>
                                        {/* Create Event & Add Event  */}
                                        {currTab === "event" && (
                                          <div className="overflow-auto flex-col" style={{ marginLeft: "-10px" }}>
                                            <div className="flex-col justify-start gap-5 inline-flex" style={{ height: "47rem" }}>
                                              <div className="ElementUploader self-stretch rounded-2xl justify-start items-center gap-2.5 inline-flex" style={{ borderRadius: "15px" }}>
                                                {passport && (
                                                  <>
                                                    <FileViewer
                                                      fileId={passport}
                                                      label="Image"
                                                      name="passport"
                                                      style={{
                                                        padding: "0px !important",
                                                        border: "none !important",
                                                      }}
                                                      handleFile={set_passport}
                                                    />
                                                  </>
                                                )}
                                                {!passport && (<FileUploadWithDropArea maxSize={2} fileTypes={"JPG,PNG"} style={{ padding: "0px !important", border: "none !important", }} linkUploadedFile={set_passport} />)}
                                                <div className="IconsDelete w-6 h-6 relative rounded-3xl" />
                                              </div>
                                              <div className={`Frame11853 ${isMobile ? 'w-full' : 'w-96'} justify-start items-start gap-2.5 inline-flex`}>
                                                <div className="col-span-2 w-1/2">
                                                  <label className="labels-children">NAME</label>
                                                  <MyTextInput className="children-inputs" name="name" type="text" required={true} placeholder="Name"
                                                  />
                                                </div>
                                                <div className="col-span-2 w-1/2">
                                                  <label className="labels-children">DATE</label>
                                                  <MyTextInput className="children-inputs" name="event_date" type="date" max={""} required={true} onFocus={handleFocusStartDate}
                                                    onBlur={handleBlurStartDate} />
                                                </div>
                                              </div>
                                              <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex">
                                                <div className="w-1/2">
                                                  <label className="labels">Start At</label>
                                                  <MyTextInput name="event_start_time" type="time" className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex" required={true} />
                                                </div>
                                                <div className="w-1/2">
                                                  <label className="labels">End At</label>
                                                  <MyTextInput name="event_end_time" type="time" className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex" required={true} />
                                                </div>
                                              </div>
                                              <EventMode eventType={eventType} setEventType={setEventType} />
                                              {eventType === "ON CAMPUS" ?
                                                <OnCampusEventAndTour schools={schools} setSchoolLocation={setSchoolLocation} setLat={setLat} setLng={setLng} Lat={Lat} Lng={Lng} googleMapPin={googleMapPin} /> :
                                                <div className={`InputsBasicInputFull ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex`}>
                                                  <div className="col-span-2 w-full">
                                                    <label className="labels-children">MEETING LINK</label>
                                                    <MyTextInput className="children-inputs" name="meeting_url" type="text" required={true} placeholder="Address Here" />
                                                  </div>
                                                </div>
                                              }
                                              <div className={`InputsBasicInputFull12 ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex space-x-3`} style={{ marginTop: eventType === "ON CAMPUS" ? "17rem" : "4rem" }}>
                                                <div class="w-full">
                                                  <label className="labels">DESRIPTION</label>
                                                  <textarea value={description} onChange={(e) => setDescription(e.target.value)} className="input-textarea" name="description" type="textarea" rows={4} placeholder="Description" maxLength={200} required={true}></textarea>
                                                  <p className="get-text-area-comment flex justify-end">{description?.length > 0 ? description?.length : 0}/200</p>
                                                </div>
                                              </div>
                                              <button type="submit" color="primary" className="button button-default" style={{ minHeight: "2.5rem", border: "1px solid #F1735F", }} onClick={() => {
                                                // setModalMessage(`${currTabName == "Tour" ? "Tour" : "Event"} created successfully!!`)
                                                // setConfirmModel(true)
                                                // setConfirmLbl("Go to Calendar")
                                                // setCancelLbl("Stay On School Page")
                                              }}>
                                                Create
                                              </button>
                                            </div>
                                          </div>
                                        )}
                                        {currTab === "tour" && (
                                          <div className="overflow-auto flex-col" style={{ marginLeft: `${!isMobile ? "-10px" : ''}` }}>
                                            <div className={`flex-col justify-start gap-5 ${isMobile ? 'w-full' : ''} inline-flex`} style={{ height: "47rem" }}                                          >
                                              <div className="TourSchedule w-56 text-slate-900 text-sm font-semibold font-['Poppins-Regular'] leading-tight">
                                                Tour Schedule
                                              </div>
                                              {/* Slot View on Tour list */}
                                              {newTourData?.map((data, i) => {
                                                return (
                                                  <div className={`Frame11856 ${isMobile ? 'w-full' : 'w-96'} h-14 p-3 bg-slate-100 rounded-lg flex-col justify-center items-start gap-5 inline-flex`}>
                                                    <div className="Frame11852 self-stretch justify-start items-center gap-2.5 inline-flex">
                                                      <div className="ElementFilterSelector grow shrink basis-0 h-8 justify-start items-center gap-2.5 flex min-w-full">
                                                        <div className="IconsCalendarBig w-8 h-6 relative mr-auto">
                                                          <img src="/images/calendar-big.svg" alt="calender" className="w-9 h-7" />
                                                        </div>
                                                        <div className="Frame12481 flex-col justify-start items-start inline-flex">
                                                          <div className="Frame12528 justify-start items-start gap-2 flex flex-col">
                                                            <div className="MondayWednesdayFriday text-slate-900 text-xs font-medium font-['Poppins'] uppercase leading-3">{data?.name}</div>
                                                            <div className="MondayWednesdayFriday text-slate-900 text-xs font-light font-['Poppins'] uppercase leading-3">{data.slot_start_time} - {data.slot_end_time} </div>
                                                          </div>
                                                        </div>
                                                        <div className="IconsEdit w-8 h-6 relative ml-auto">
                                                          <img onClick={() => {
                                                            handleScheduleEditClick(data,'NewSlot')
                                                          }} src="/images/edit.svg" alt="calender" className="w-9 h-7 cursor-pointer" />
                                                        </div>
                                                      </div>
                                                      <div className="IconsEdit w-6 h-6 relative" />
                                                    </div>
                                                  </div>
                                                )
                                              })}
                                              {console.log("startDates......",startDates)}
                                              {/* Add Tour Slot */}
                                              {!slotEditMode && isSaveBtn &&
                                                <>
                                                  <Formik
                                                    initialValues={{
                                                      slot_name: slotInitialValue?.slotName,
                                                      weekdays: slotInitialValue?.weekdays,
                                                      slot_start_date: slotInitialValue?.slotStartDate,
                                                      slot_end_date: slotInitialValue?.slotEndDate,
                                                      slot_start_time: slotInitialValue?.slotStartTime,
                                                      slot_end_time: slotInitialValue?.slotEndTime,
                                                      slot_id: slotInitialValue?.id
                                                    }}
                                                  validationSchema={Yup.object({
                                                    // slot_name: Yup.string().required("Name Field Required"),
                                                    // weekdays: Yup.array().of(Yup.string()).required("Days Field Required").min(1, "At least one day is required"),
                                                    // slot_start_date: Yup.string().required("Date Field Required"),
                                                    // slot_start_time: Yup.string().required("Start Time Field Required"),
                                                    // slot_end_time: Yup.string().required("End Time Field Required"),
                                                    slot_start_time : Yup.string().required('Start time is required'),
                                                    slot_end_time: Yup.string()
                                                      .required('End time is required')
                                                      .test(
                                                        'time-difference',
                                                        'The difference between start and end time should be at least 30 minute',
                                                        function (value) {
                                                          const { slot_start_time } = this.parent;
                                                          if (slot_start_time && value) {
                                                            const startTime = new Date(`1970-01-01T${slot_start_time}`);
                                                            const endTime = new Date(`1970-01-01T${value}`);
                                                            const timeDifference = endTime - startTime;
                                                            const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                                                            return timeDifference >= minimumDifference;
                                                          }
                                                          return true;
                                                        }
                                                      ),
                                                    slot_start_date: Yup.date()
                                                      .min(tomorrowDateTourEvent(), "Start Date needs to be a future date")
                                                      .required('Required'),
                                                    slot_end_date: Yup.date()
                                                      // .required("Date of Birth is required")
                                                      .test("futur-date", "End Date needs to be a future date", (value) => {
                                                        const date = new Date();
                                                        date.setDate(date.getDate() - 1);
                                                        return !value || value >= date;
                                                      })
                                                      .when("slot_start_date", {
                                                        is: (val) => val,
                                                        then: Yup.date()
                                                          .min((startDates), "End date need to be equal or greater then start date")
                                                      })
                                                  })}
                                                    onSubmit={(values, actions) => {
                                                    }}
                                                  >
                                                    {/* Add New Tour Slots */}
                                                    {({ values, errors }) => (
                                                      <Form>                   
                                                    <div>
                                                        <div className="InputsBasicInputEmpty self-stretch h-10 flex-col justify-end flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-full">
                                                            <label className="labels-children">
                                                              NAME
                                                            </label>
                                                            <MyTextInput className="children-inputs" name="slot_name" type="text" placeholder="Name" required={true} />
                                                          </div>
                                                        </div>
                                                        <div className="Frame12527 justify-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-full">
                                                            <label className="labels-children">Week Days</label>
                                                            <Field
                                                              name="weekdays"
                                                              required={true}
                                                              render={({ field, form }) => {
                                                                let selectedOptions = null
                                                                if (field?.value?.length > 0) {
                                                                  selectedOptions = field?.value?.map((selectedValue) => {
                                                                    const selectedOption = days.find((day) => day.value === selectedValue);
                                                                    return selectedOption || null;
                                                                  })
                                                                }
                                                                return (
                                                                  <Select
                                                                    {...field}
                                                                    isMulti
                                                                    className="custom-select"
                                                                    options={days}
                                                                    onChange={(selectedOptions) => {
                                                                      form.setFieldValue("weekdays", selectedOptions.map((option) => option.value));
                                                                    }}
                                                                    value={selectedOptions}
                                                                  />
                                                                );
                                                              }}
                                                            />
                                                          </div>
                                                        </div>
                                                        <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-1/2">
                                                            <label className="labels-children">
                                                              Start Date
                                                            </label>
                                                            <MyTextInput
                                                              className="children-inputs input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                              name="slot_start_date"
                                                              type="date"
                                                              min={tomorrowDateTourEvent()}
                                                              required={true}
                                                              onFocus={handleFocusStartDate}
                                                              onBlur={handleBlurStartDate}
                                                              StartDates={setStartDate}
                                                            />
                                                            <span className="text-sm">{errors?.slot_start_date}</span>
                                                          </div>
                                                          <div className="col-span-2 w-1/2">
                                                            <label className="labels-children">
                                                              End Date (Optional)
                                                            </label>
                                                            <MyTextInput
                                                              className="children-inputs input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                              name="slot_end_date"
                                                              type="date"
                                                              min={tomorrowDateTourEvent()}
                                                              // onChange={((e)=>{console.log(e);})}
                                                              onFocus={handleFocusStartDate}
                                                              onBlur={handleBlurStartDate}
                                                            />
                                                            <span className="text-sm">{errors?.slot_end_date}</span>
                                                          </div>
                                                        </div>
                                                        <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="w-1/2">
                                                            <label className="labels">
                                                              Time from
                                                            </label>
                                                            <MyTextInput
                                                              name="slot_start_time"
                                                              type="time"
                                                              className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                              required={true}
                                                            />
                                                          </div>
                                                          <div className="w-1/2">
                                                            <label className="labels">
                                                              Time to
                                                            </label>
                                                            <MyTextInput
                                                              name="slot_end_time"
                                                              type="time"
                                                              required={true}
                                                              className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                            />
                                                          </div>
                                                        </div>
                                                        <button
                                                          type="button"
                                                          onClick={() => {(errors?.slot_end_time || errors?.slot_start_date) ? '' :handleCreateSlots(values,"NewSlot")}}
                                                          className="flex w-100 h-100 Apply origin-center text-white text-sm font-semibold font-['Poppins'] items-center	ButtonsPrimaryDisabled mt-3  self-stretch bg-red-400 rounded-2xl  border flex-col justify-center items-center flex" style={{ color: "white", minHeight: "2.5rem", border: "1px solid #F1735F", width: "100%" }}
                                                        >Save</button>
                                                      </div>
                                                      </Form>
                                                  )}
                                                  </Formik>
                                                </>
                                              }
                                              {/* Edit Tour Slot */}
                                              {slotEditMode &&
                                                <>
                                                  <Formik
                                                    initialValues={{
                                                      slot_name: slotInitialValue?.slotName,
                                                      weekdays: slotInitialValue?.weekdays,
                                                      slot_start_date: slotInitialValue?.slotStartDate,
                                                      slot_end_date: slotInitialValue?.slotEndDate,
                                                      slot_start_time: slotInitialValue?.slotStartTime,
                                                      slot_end_time: slotInitialValue?.slotEndTime,
                                                      slot_id: slotInitialValue?.id
                                                    }}
                                                    validationSchema={Yup.object({
                                                      // slot_name: Yup.string().required("Name Field Required"),
                                                      // weekdays: Yup.array().of(Yup.string()).required("Days Field Required").min(1, "At least one day is required"),
                                                    slot_start_time : Yup.string().required('Start time is required'),
                                                    slot_end_time: Yup.string()
                                                    .required('End time is required')
                                                    .test(
                                                      'time-difference',
                                                      'The difference between start and end time should be at least 30 minute',
                                                      function (value) {
                                                        const { slot_start_time } = this.parent;
                                                        if (slot_start_time && value) {
                                                          const startTime = new Date(`1970-01-01T${slot_start_time}`);
                                                          const endTime = new Date(`1970-01-01T${value}`);
                                                          const timeDifference = endTime - startTime;
                                                          const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                                                          return timeDifference >= minimumDifference;
                                                        }
                                                        return true;
                                                      }
                                                    ),
                                                    slot_start_date: Yup.date()
                                                      .min(tomorrowDateTourEvent(), "Start Date needs to be a future date")
                                                      .required('Required'),
                                                    slot_end_date: Yup.date()
                                                      // .required("Date of Birth is required")
                                                      .test("futur-date", "End Date needs to be a future date", (value) => {
                                                        const date = new Date();
                                                        date.setDate(date.getDate() - 1);
                                                        return !value || value >= date;
                                                      })
                                                      .when("slot_start_date", {
                                                        is: (val) => val,
                                                        then: Yup.date()
                                                          .min((startDates), "End date need to be equal or greater then start date")
                                                      })
                                                    })}
                                                    onSubmit={(values, actions) => {
                                                      currTab === "event" ?
                                                        handleEventSubmit(values) :
                                                        handleTourSubmit(values);
                                                      return;
                                                    }}
                                                  >
                                                    {({ values, errors }) => (
                                                      <Form>
                                                    <div>
                                                        <div className="InputsBasicInputEmpty self-stretch h-10 flex-col justify-end flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-full">
                                                            <label className="labels-children">
                                                              NAME
                                                            </label>
                                                            <MyTextInput className="children-inputs" name="slot_name" type="text" required={true} placeholder="Name" />
                                                          </div>
                                                        </div>
                                                        <div className="Frame12527 justify-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-full">
                                                            <label className="labels-children">Week Days</label>
                                                            <Field
                                                              name="weekdays"
                                                              render={({ field, form }) => {
                                                                const selectedOptions = field?.value?.map((selectedValue) => {
                                                                  const selectedOption = days.find((day) => day.value === selectedValue);
                                                                  return selectedOption || null;
                                                                });
                                                                return (
                                                                  <Select
                                                                    {...field}
                                                                    isMulti
                                                                    className="custom-select"
                                                                    options={days}
                                                                    onChange={(selectedOptions) => {
                                                                      form.setFieldValue("weekdays", selectedOptions.map((option) => option.value));
                                                                    }}
                                                                    value={selectedOptions}
                                                                  />
                                                                );
                                                              }}
                                                            />
                                                          </div>
                                                        </div>
                                                        <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="col-span-2 w-1/2">
                                                            <label className="labels-children">
                                                              Start Date
                                                            </label>
                                                            <MyTextInput
                                                              className="children-inputs  input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                              name="slot_start_date"
                                                              type="date"
                                                              min={tomorrowDateTourEvent()}
                                                              required={true}
                                                              onFocus={handleFocusStartDate}
                                                              onBlur={handleBlurStartDate}
                                                              StartDates={setStartDate}
                                                            />
                                                            <span className="text-sm">{errors?.slot_start_date}</span>
                                                          </div>
                                                          <div className="col-span-2 w-1/2">
                                                            <label className="labels-children">
                                                              End Date (Optional)
                                                            </label>
                                                            <MyTextInput
                                                              className="children-inputs  input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                              name="slot_end_date"
                                                              type="date"
                                                              min={tomorrowDateTourEvent()}
                                                              onFocus={handleFocusStartDate}
                                                              onBlur={handleBlurStartDate}
                                                            />
                                                            <span className="text-sm">{errors?.slot_end_date}</span>
                                                          </div>
                                                        </div>
                                                        <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                          <div className="w-1/2">
                                                            <label className="labels">
                                                              Time from
                                                            </label>
                                                            <MyTextInput
                                                              name="slot_start_time"
                                                              type="time"
                                                              className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                            />
                                                          </div>
                                                          <div className="w-1/2">
                                                            <label className="labels">
                                                              Time to
                                                            </label>
                                                            <MyTextInput
                                                              name="slot_end_time"
                                                              type="time"
                                                              className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                            />
                                                          </div>
                                                        </div>
                                                        {/* <button
                                                        type="button"
                                                        onClick={() => handleCreateSlots(values)} // Call the function when the button is clicked
                                                        className="flex w-100 h-100 Apply origin-center text-white text-sm font-semibold font-['Poppins'] items-center	ButtonsPrimaryDisabled mt-3  self-stretch bg-red-400 rounded-2xl  border flex-col justify-center items-center flex" style={{ color: "white", minHeight: "2.5rem", border: "1px solid #F1735F", width: "100%" }}
                                                      >Save</button> */}
                                                       <button
                                                        type="button"
                                                        onClick={() => {errors?.slot_end_time ? '' :handleCreateSlots(values,"NewEditSlot")}}
                                                        className="flex w-100 h-100 Apply origin-center text-white text-sm font-semibold font-['Poppins'] items-center	ButtonsPrimaryDisabled mt-3  self-stretch bg-red-400 rounded-2xl  border flex-col justify-center items-center flex" style={{ color: "white", minHeight: "2.5rem", border: "1px solid #F1735F", width: "100%" }}
                                                      >Save</button>
                                                      {/* </div> */}
                                                    </div>
                                                    </Form>
                                                  )}
                                                </Formik>
                                              </>
                                            }
                                            {!isSaveBtn && !slotEditMode &&
                                              <div
                                                className="ButtonsPrimaryDisabled origin-center self-stretch min-h-15 h-15 rounded-2xl border flex-col justify-center items-center flex"
                                                style={{
                                                  minHeight: "2.5rem",
                                                  border: "1px solid #F1735F",
                                                }}
                                              >
                                                {/* <button
                                                type="button"
                                                onClick={handleAddslotClick} // Call the function when the button is clicked
                                                className="flex w-100 h-100 Apply  origin-center rotate-180 text-white text-sm font-semibold font-['Poppins'] items-center"
                                                style={{ color: "#F1735F" }}
                                              >
                                                Add Slot
                                                <span>
                                                  <img src="/images/plusorange.png" alt="plus" className="ml-2" style={{ color: "#F1735F" }} />
                                                </span>
                                              </button> */}

                                                <button
                                                  type="button"
                                                  onClick={() => handleAddslotClick()}
                                                  className="flex w-100 h-100 Apply text-white text-sm font-semibold font-['Poppins'] items-center origin-center self-stretch rounded-2xl border justify-center"
                                                  style={{ color: "#F1735F", minHeight: "2.5rem", border: "1px solid #F1735F", }}
                                                >
                                                  Add Slot
                                                  <img
                                                    src="/images/plusorange.png"
                                                    alt="plus"
                                                    className="ml-2"
                                                    style={{ color: "#F1735F" }}
                                                  />
                                                </button>

                                              </div>
                                            }
                                            <div className={`Section ${isMobile ? 'w-full' : 'w-96'} h-32 flex-col justify-start items-start gap-5 inline-flex`}>
                                              <div className="Location w-56 text-slate-900 text-sm font-semibold font-['Poppins-Regular'] leading-tight">
                                                Location
                                              </div>
                                              <EventMode eventType={eventType} setEventType={setEventType} />
                                              {eventType === "ON CAMPUS" ?
                                                <OnCampusEventAndTour schools={schools} setSchoolLocation={setSchoolLocation} setLat={setLat} setLng={setLng} Lat={Lat} Lng={Lng} googleMapPin={googleMapPin} />
                                                : <div className={`InputsBasicInputFull ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex`}>
                                                  <div className="col-span-2 w-full">
                                                    <label className="labels-children">
                                                      MEETING LINK
                                                    </label>
                                                    <MyTextInput
                                                      className="children-inputs"
                                                      name="meeting_url"
                                                      type="text"
                                                      required={true}
                                                      placeholder="Address Here"
                                                    />
                                                  </div>
                                                </div>}
                                            </div>
                                            <div className="flex" style={{ marginTop: eventType === "ON CAMPUS" ? "17rem" : "0rem" }} >
                                              {/* <div className="h-0 w-0 TourSchedule1 text-slate-900 text-sm font-semibold font-['Poppins-Regular'] leading-tight" style={eventType === "ON CAMPUS" ? { marginTop: "10px", marginBottom: "0px" } : {}}>
                                                Other
                                              </div>
                                              <div className={`Checkboxes1 ${isMobile ? 'w-full' : 'w-96'} justify-start items-start inline-flex mt-8`}>
                                                <div class=" flex" >
                                                <label class="flex items-center ">
                                                    <input type="radio" onClick={() => setOtherType("Group Tour")} class="form-radio square-radio" name="tour_type" value="option2" checked={otherType == "Group Tour" && true} />
                                                    <span class="ml-2">Group Tour</span>
                                                  </label>
                                                  <label class="flex items-center ml-4">
                                                    <input onClick={() => setOtherType("Individual")} type="radio" class=" form-radio square-radio" name="tour_type" value="option1" checked={otherType == "Individual" && true} />
                                                    <span class="ml-2">Individual</span>
                                                  </label>
                                                </div>
                                              </div> */}
                                            </div>
                                            <div class="w-full">
                                              <label className="labels">
                                                DESRIPTION
                                              </label>
                                              <textarea
                                                value={description}
                                                onChange={(e) => setDescription(e.target.value)}
                                                className="input-textarea"
                                                name="description"
                                                type="textarea"
                                                rows={4}
                                                placeholder="Description"
                                                maxLength={200}
                                              >
                                              </textarea>
                                              <p className="get-text-area-comment flex justify-end">
                                                {description?.length > 0 ? description?.length : 0}/200
                                              </p>
                                            </div>
                                            <button type="submit" color="primary" className="button button-default" style={{ minHeight: "2.5rem", border: "1px solid #F1735F", }} onClick={() => {
                                              // setModalMessage(`${currTabName == "Tour" ? "Tour" : "Event"} created successfully!!`)
                                              // // setConfirmModel(true)
                                              // setConfirmLbl("Go to Calendar")
                                              // setCancelLbl("Stay On School Page")
                                            }}>
                                              Create
                                            </button>
                                          </div>
                                        </div>
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Form>
                    )}
                  </Formik>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition.Root>

      {/* Edit Event and tour Modal */}
      <Transition.Root show={editOpen} as={Fragment}>
        <Dialog as="div" className="relative z-10" onClose={setEditOpen}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
          </Transition.Child>

          <div className="fixed z-10 inset-0 overflow-y-auto">
            <div className="flex items-end sm:items-center justify-center min-h-full p-4 text-center sm:p-0">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                enterTo="opacity-100 translate-y-0 sm:scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 translate-y-0 sm:scale-100"
                leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
              >
                <Dialog.Panel
                  className="relative bg-white rounded-lg  text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:max-w-lg sm:w-full sm:p-0"
                  style={{ maxHeight: "55rem", maxWidth: "41rem" }}
                >
                  <Formik
                    initialValues={{
                      name: eventTourEditData?.name,
                      event_start_time: eventTourEditData?.event_start_time,
                      event_end_time: eventTourEditData?.event_end_time,
                      event_date: new Date(eventTourEditData?.event_date),
                      address: eventTourEditData?.address,
                      description: eventTourEditData?.description,
                      meeting_url: eventTourEditData?.meeting_url,
                      google_map_pin: eventTourEditData?.google_map_pin,
                      event_date: eventTourEditData?.event_date,
                      fully_booked: eventTourEditData?.fully_booked,
                      banner: eventTourEditData?.banner,
                    }}
                    validationSchema={Yup.object().shape({
                      event_start_time: currTab === "event" ? Yup.string().required('Start time is required') : Yup.string(),
                      event_end_time: currTab === "event" ? Yup.string()
                        .required('End time is required')
                        .test(
                          'time-difference',
                          'The difference between start and end time should be at least 30 minutes',
                          function (value) {
                            const { event_start_time } = this.parent;
                            console.log("value..event_start_time...",value ,event_start_time);
                            if (event_start_time && value) {
                              const startTime = new Date(`1970-01-01T${event_start_time}`);
                              const endTime = new Date(`1970-01-01T${value}`);
                              const timeDifference = endTime - startTime;
                              const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                              return timeDifference >= minimumDifference;
                            }
                            return true;
                          }
                        ):Yup.string()
                    })}
                    onSubmit={(values, actions) => {
                      currTab === "event" ?
                        handleEditClick(values, "events") :
                        handleTourEdit(values, "tours");
                      return;
                    }}
                  >
                    {(values) => (
                      <Form>
                        <div className="flex flex-row">
                          <div className="w/1-4 edit-event-image">
                            <img
                              className="h-full"
                              src="/images/FrameEventEdit.png"
                              alt="OSS Sign In"
                            />
                          </div>
                          <div
                            className={`flex flex-col ${isMobile ? 'w-full' : 'w-3/4'} overflow-y-scroll`}
                            style={{ height: "55rem" , width: `${isMobile ? '41rem' : ''}`}}
                          >
                            <div className="flex items-center justify-between m-3">
                              <div className="mt-1 ml-1 text-2xl font-extrabold text-gray-900">
                                Edit{currTabName === "Event" ? " an Event" : " a Tour"}
                              </div>
                              <button
                                type="button"
                                className=" text-bold"
                                onClick={() => {
                                  setEditOpen(false);
                                }}
                              >
                                <XIcon className="w-4 h-4" />
                              </button>
                            </div>
                            <div
                              className="bg-white py-4 flex items-center justify-between p-7"
                              style={{ overflow: "scroll", height: "45rem" }}
                            >
                              <div
                                className="Inputs bg-white rounded-lg flex-col justify-start items-start gap-3 inline-flex"
                                style={{ height: "43rem", width: "100%" }}
                              >
                                {/* <div className="ElementWizard h-2 justify-start items-center gap-1.5 inline-flex">
                                  <MyCheckbox
                                    name="fully_booked" style={{ position: "sticky"}}
                                    disabled={false}
                                  />
                                  <div className="Yes text-slate-900 text-xs font-normal font-['Poppins-Regular'] leading-none">
                                    Mark as Fully Booked.
                                  </div>
                                </div> */}
                                {currTabName == "Tour" && (
                                  <div className="TourSchedule mt-3 w-56 text-slate-900 text-sm font-semibold font-['Poppins-Regular'] leading-tight">
                                    Tour Schedule
                                  </div>
                                )}
                                <div className={`Section flex-col justify-start items-start gap-2.5 flex ${isMobile ? 'w-full' : ''}`}>
                                  {currTabName == "Event" && (
                                    <div className="ElementUploader self-stretch p-2.5 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex">
                                      {passport && (
                                        <>
                                          <FileViewer
                                            fileId={passport}
                                            label="Image"
                                            name="passport"
                                            style={{
                                              padding: "0px !important",
                                              border: "none !important",
                                            }}
                                            handleFile={set_passport}
                                          />
                                        </>
                                      )}
                                      {!passport && (
                                        <>
                                          <FileUploadWithDropArea
                                            maxSize={2}
                                            fileTypes={"JPG,PNG"}
                                            style={{
                                              padding: "0px !important",
                                              border: "none !important",
                                            }}
                                            linkUploadedFile={set_passport}
                                          />
                                        </>
                                      )}
                                      <div className="IconsDelete w-6 h-6 relative rounded-3xl" />
                                    </div>
                                  )}
                                  {currTabName === "Event" && (
                                    <>
                                      <div className={`Frame11853 ${isMobile ? 'w-full' : 'w-96'} justify-start items-start gap-2.5 inline-flex`}>
                                        <div className="col-span-2 w-1/2">
                                          <label className="labels-children">
                                            NAME
                                          </label>
                                          <MyTextInput
                                            className="children-inputs"
                                            name="name"
                                            type="text"
                                            required={true}
                                            placeholder="Name"
                                          />
                                        </div>
                                        <div className="col-span-2 w-1/2">
                                          <label className="labels-children">
                                            DATE
                                          </label>
                                          <MyTextInput className="children-inputs" name="event_date" type="date" max={""} required={true} onFocus={handleFocusStartDate} onBlur={handleBlurStartDate} />
                                        </div>
                                      </div>
                                      <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex">
                                        <div className="w-1/2">
                                          <label className="labels">Start At</label>
                                          <MyTextInput name="event_start_time" type="time" className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex" />
                                        </div>
                                        <div className="w-1/2">
                                          <label className="labels">End At</label>
                                          <MyTextInput name="event_end_time" type="time" className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex" />
                                        </div>
                                      </div>
                                    </>
                                  )}

                                  {/* Tour Scheduled Slots */}
                                  {currTabName === "Tour" && slotsDetails?.map((data, i) => {
                                    return (
                                      <div className={`Frame11856 ${isMobile ? 'w-full' : 'w-96'} h-14 p-3 bg-slate-100 rounded-lg flex-col justify-center items-start gap-5 inline-flex`}>
                                        <div className="Frame11852 self-stretch justify-start items-center gap-2.5 inline-flex">
                                          <div className="ElementFilterSelector grow shrink basis-0 h-8 justify-start items-center gap-2.5 flex min-w-full">
                                            <div className="IconsCalendarBig w-8 h-6 relative mr-auto">
                                              <img src="/images/calendar-big.svg" alt="calender" className="w-9 h-7" />
                                            </div>
                                            <div className="Frame12481 flex-col justify-start items-start inline-flex">
                                              <div className="Frame12528 justify-start items-start gap-2 flex flex-col">
                                                <div className="MondayWednesdayFriday text-slate-900 text-xs font-medium font-['Poppins'] uppercase leading-3">{data?.slot?.name}</div>
                                                <div className="MondayWednesdayFriday text-slate-900 text-xs font-light font-['Poppins'] uppercase leading-3">{data?.slot?.slot_start_time} - {data?.slot?.slot_end_time} </div>
                                              </div>
                                            </div>
                                            <div className="IconsEdit w-8 h-6 relative ml-auto">
                                              <img onClick={() => {
                                                handleScheduleEditClick(data.slot, "Slot Update")
                                              }} src="/images/edit.svg" alt="calender" className="w-9 h-7 cursor-pointer" />
                                            </div>
                                          </div>
                                          <div className="IconsEdit w-6 h-6 relative" />
                                        </div>
                                      </div>
                                    )
                                  })}
                                  {currTabName === "Tour" && newTourData?.map((data, i) => {
                                    return (
                                      <div className={`Frame11856 ${isMobile ? 'w-full' : 'w-96'} h-14 p-3 bg-slate-100 rounded-lg flex-col justify-center items-start gap-5 inline-flex`}>
                                        <div className="Frame11852 self-stretch justify-start items-center gap-2.5 inline-flex">
                                          <div className="ElementFilterSelector grow shrink basis-0 h-8 justify-start items-center gap-2.5 flex min-w-full">
                                            <div className="IconsCalendarBig w-8 h-6 relative mr-auto">
                                              <img src="/images/calendar-big.svg" alt="calender" className="w-9 h-7" />
                                            </div>
                                            <div className="Frame12481 flex-col justify-start items-start inline-flex">
                                              <div className="Frame12528 justify-start items-start gap-2 flex flex-col">
                                                <div className="MondayWednesdayFriday text-slate-900 text-xs font-medium font-['Poppins'] uppercase leading-3">{data?.name}</div>
                                                <div className="MondayWednesdayFriday text-slate-900 text-xs font-light font-['Poppins'] uppercase leading-3">{data?.slot_start_time} - {data?.slot_end_time} </div>
                                              </div>
                                            </div>
                                            <div className="IconsEdit w-8 h-6 relative ml-auto">
                                              <img onClick={() => {
                                                handleScheduleEditClick(data, "Slot Update")
                                              }} src="/images/edit.svg" alt="calender" className="w-9 h-7 cursor-pointer" />
                                            </div>
                                          </div>
                                          <div className="IconsEdit w-6 h-6 relative" />
                                        </div>
                                      </div>
                                    )
                                  })}
                                  {/* Edit Tour Schedule Add Slot */}
                                  {!slotEditMode && isSaveBtn && currTabName === "Tour" &&
                                      <>
                                        <Formik
                                          initialValues={{
                                            slot_name: slotInitialValue?.slotName,
                                            weekdays: slotInitialValue?.weekdays,
                                            slot_start_date: slotInitialValue?.slotStartDate,
                                            slot_end_date: slotInitialValue?.slotEndDate,
                                            slot_start_time: slotInitialValue?.slotStartTime,
                                            slot_end_time: slotInitialValue?.slotEndTime,
                                            slot_id: slotInitialValue?.id
                                          }}
                                          validationSchema={Yup.object().shape({
                                            slot_start_time: Yup.string().required('Start time is required'),
                                            slot_end_time: Yup.string()
                                              .required('End time is required')
                                              .test(
                                                'time-difference',
                                                'The difference between start and end time should be at least 30 minute',
                                                function (value) {
                                                  const { slot_start_time } = this.parent;
                                                  if (slot_start_time && value) {
                                                    const startTime = new Date(`1970-01-01T${slot_start_time}`);
                                                    const endTime = new Date(`1970-01-01T${value}`);
                                                    const timeDifference = endTime - startTime;
                                                    const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                                                    return timeDifference >= minimumDifference;
                                                  }
                                                  return true;
                                                }
                                              ),
                                            slot_start_date: Yup.date()
                                              .min(tomorrowDateTourEvent(), "Start Date needs to be a future date")
                                              .required('Required'),
                                            slot_end_date: Yup.date()
                                              // .required("Date of Birth is required")
                                              .test("futur-date", "End Date needs to be a future date", (value) => {
                                                const date = new Date();
                                                date.setDate(date.getDate() - 1);
                                                return !value || value >= date;
                                              })
                                              .when("slot_start_date", {
                                                is: (val) => val,
                                                then: Yup.date()
                                                  .min((startDates), "End date need to be equal or greater then start date")
                                              })
                                          })}
                                          onSubmit={(values, actions) => {
                                            currTab === "event" ?
                                              handleEventSubmit(values) :
                                              handleTourSubmit(values);
                                            return;
                                          }}
                                        >
                                          {({ values, errors }) => (
                                            <Form className="w-full">
                                              {console.log("errors.....",errors)}
                                            <>
                                              <div className="InputsBasicInputEmpty self-stretch h-10 flex-col justify-end flex mt-3">
                                                <div className="col-span-2 w-full">
                                                  <label className="labels-children">
                                                    NAME
                                                  </label>
                                                  <MyTextInput className="children-inputs" name="slot_name" type="text" required={true} placeholder="Name" />
                                                </div>
                                              </div>
                                              <div className="Frame12527 justify-start gap-2.5 inline-flex" style={{ minWidth: "99%" }}>
                                                <div className="col-span-2 w-full">
                                                  <label className="labels-children">Week Days</label>
                                                  <Field
                                                    name="weekdays"
                                                    render={({ field, form }) => {
                                                      const selectedOptions = field?.value?.map((selectedValue) => {
                                                        const selectedOption = days.find((day) => day.value === selectedValue);
                                                        return selectedOption || null;
                                                      });
                                                      return (
                                                        <Select
                                                          {...field}
                                                          isMulti
                                                          className="custom-select"
                                                          options={days}
                                                          onChange={(selectedOptions) => {
                                                            form.setFieldValue("weekdays", selectedOptions.map((option) => option.value));
                                                          }}
                                                          value={selectedOptions}
                                                        />
                                                      );
                                                    }}
                                                  />

                                                </div>
                                              </div>
                                              <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex" style={{ minWidth: "99%" }}>
                                                <div className="col-span-2 w-1/2">
                                                  <label className="labels-children">
                                                    Start Date
                                                  </label>
                                                  <MyTextInput
                                                    className="children-inputs  input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                    name="slot_start_date"
                                                    type="date"
                                                    min={tomorrowDateTourEvent()}
                                                    required={true}
                                                    onFocus={handleFocusStartDate}
                                                    onBlur={handleBlurStartDate}
                                                    StartDates={setStartDate}
                                                  />
                                                  <span className="text-sm">{errors?.slot_start_date}</span>
                                                </div>
                                                <div className="col-span-2 w-1/2">
                                                  <label className="labels-children">
                                                    End Date (Optional)
                                                  </label>
                                                  <MyTextInput
                                                    className="children-inputs  input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                    name="slot_end_date"
                                                    type="date"
                                                    min={tomorrowDateTourEvent()}
                                                    onFocus={handleFocusStartDate}
                                                    onBlur={handleBlurStartDate}
                                                  />
                                                  <span className="text-sm">{errors?.slot_end_date}</span>
                                                </div>

                                              </div>
                                              <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                                <div className="w-1/2">
                                                  <label className="labels">
                                                    Time from
                                                  </label>
                                                  <MyTextInput
                                                    name="slot_start_time"
                                                    type="time"
                                                    className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                  />
                                                </div>
                                                <div className="w-1/2">
                                                  <label className="labels">
                                                    Time to
                                                  </label>
                                                  <MyTextInput
                                                    name="slot_end_time"
                                                    type="time"
                                                    className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                  />
                                                </div>
                                              </div>
                                              {/* <div
                                        className="ButtonsPrimaryDisabled origin-center self-stretch min-h-15 h-15 -rotate-180 bg-red-400 rounded-2xl  border flex-col justify-center items-center flex"
                                        style={{ minHeight: "2.5rem", border: "1px solid #F1735F" }}> */}
                                              <button
                                                type="button"
                                                onClick={() => { errors?.slot_end_time ? '' : handleCreateSlots(values,"EditInCreateNewTour") }}
                                                className="flex w-100 h-100 Apply origin-center text-white text-sm font-semibold font-['Poppins'] items-center	ButtonsPrimaryDisabled mt-3  self-stretch bg-red-400 rounded-2xl  border flex-col justify-center items-center flex" style={{ color: "white", minHeight: "2.5rem", border: "1px solid #F1735F", width: "100%" }}
                                              >Save</button>
                                            </>
                                          </Form>
                                        )}
                                      </Formik>
                                    </>
                                  }
                                  {/* Edit Tour Schedule Edit Slot */}
                                  {slotEditMode && currTabName === "Tour" &&
                                    <>
                                      <Formik
                                        initialValues={{
                                          slot_name: slotInitialValue?.slotName,
                                          weekdays: slotInitialValue?.weekdays,
                                          slot_start_date: slotInitialValue?.slotStartDate,
                                          slot_end_date: slotInitialValue?.slotEndDate,
                                          slot_start_time: slotInitialValue?.slotStartTime,
                                          slot_end_time: slotInitialValue?.slotEndTime,
                                          slot_id: slotInitialValue?.id
                                        }}
                                        validationSchema={Yup.object().shape({
                                          slot_start_time: Yup.string().required('Start time is required'),
                                          slot_end_time: Yup.string()
                                            .required('End time is required')
                                            .test(
                                              'time-difference',
                                              'The difference between start and end time should be at least 30 minute',
                                              function (value) {
                                                const { slot_start_time } = this.parent;
                                                if (slot_start_time && value) {
                                                  const startTime = new Date(`1970-01-01T${slot_start_time}`);
                                                  const endTime = new Date(`1970-01-01T${value}`);
                                                  const timeDifference = endTime - startTime;
                                                  const minimumDifference = 30 * 60 * 1000; // 30 minutes in milliseconds
                                                  return timeDifference >= minimumDifference;
                                                }
                                                return true;
                                              }
                                            ),
                                          slot_start_date: Yup.date()
                                            .min(tomorrowDateTourEvent(), "Start Date needs to be a future date")
                                            .required('Required'),
                                          slot_end_date: Yup.date()
                                            // .required("Date of Birth is required")
                                            .test("futur-date", "End Date needs to be a future date", (value) => {
                                              const date = new Date();
                                              date.setDate(date.getDate() - 1);
                                              return !value || value >= date;
                                            })
                                            .when("slot_start_date", {
                                              is: (val) => val,
                                              then: Yup.date()
                                                .min((startDates), "End date need to be equal or greater then start date")
                                            })
                                        })}
                                        onSubmit={(values, actions) => {
                                          currTab === "event" ?
                                            handleEventSubmit(values) :
                                            handleTourSubmit(values);
                                          return;
                                        }}
                                      >
                                        {({ values, errors }) => (
                                          <Form className="w-full">
                                            <div className="InputsBasicInputEmpty self-stretch h-10 flex-col justify-end flex mt-3" style={{ minWidth: "99%" }}>
                                              <div className="col-span-2 w-full">
                                                <label className="labels-children">
                                                  NAME
                                                </label>
                                                <MyTextInput className="children-inputs" name="slot_name" type="text" required={true} placeholder="Name" />
                                              </div>
                                            </div>
                                            <div className="Frame12527 justify-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                              <div className="col-span-2 w-full">
                                                <label className="labels-children">Week Days</label>
                                                <Field
                                                  name="weekdays"
                                                  render={({ field, form }) => {
                                                    const selectedOptions = field?.value?.map((selectedValue) => {
                                                      const selectedOption = days.find((day) => day.value === selectedValue);
                                                      return selectedOption || null;
                                                    });
                                                    return (
                                                      <Select
                                                        {...field}
                                                        isMulti
                                                        className="custom-select"
                                                        options={days}
                                                        onChange={(selectedOptions) => {
                                                          form.setFieldValue("weekdays", selectedOptions.map((option) => option.value));
                                                        }}
                                                        value={selectedOptions}
                                                      />
                                                    );
                                                  }}
                                                />

                                              </div>
                                            </div>
                                            <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                              <div className="col-span-2 w-1/2">
                                                <label className="labels-children">
                                                  Start Date
                                                </label>
                                                <MyTextInput
                                                  className="children-inputs input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                  name="slot_start_date"
                                                  type="date"
                                                  min={tomorrowDateTourEvent()}
                                                  required={true}
                                                  onFocus={handleFocusStartDate}
                                                  onBlur={handleBlurStartDate}
                                                  StartDates={setStartDate}
                                                />
                                                <span className="text-sm">{errors?.slot_start_date}</span>
                                              </div>
                                              <div className="col-span-2 w-1/2">
                                                <label className="labels-children">
                                                  End Date (Optional)
                                                </label>
                                                <MyTextInput
                                                  className="children-inputs input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                  name="slot_end_date"
                                                  type="date"
                                                  min={tomorrowDateTourEvent()}
                                                  onFocus={handleFocusStartDate}
                                                  onBlur={handleBlurStartDate}
                                                />
                                                <span className="text-sm">{errors?.slot_end_date}</span>
                                              </div>

                                            </div>
                                            <div className="Frame11854 self-stretch justify-start items-start gap-2.5 inline-flex flex" style={{ minWidth: "99%" }}>
                                              <div className="w-1/2">
                                                <label className="labels">
                                                  Time from
                                                </label>
                                                <MyTextInput
                                                  name="slot_start_time"
                                                  type="time"
                                                  className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                />
                                              </div>
                                              <div className="w-1/2">
                                                <label className="labels">
                                                  Time to
                                                </label>
                                                <MyTextInput
                                                  name="slot_end_time"
                                                  type="time"
                                                  className="input-field self-stretch pl-4 pr-2.5 py-2 rounded-2xl border border-slate-200 justify-start items-center gap-2.5 inline-flex"
                                                />
                                              </div>
                                            </div>
                                            {/* <div
                                              className="ButtonsPrimaryDisabled mt-3 origin-center self-stretch min-h-15 h-15 -rotate-180 bg-red-400 rounded-2xl  border flex-col justify-center items-center flex"
                                              style={{ minHeight: "2.5rem", border: "1px solid #F1735F" }}> */}
                                            <button
                                              type="button"
                                              onClick={() => {errors?.slot_end_time ? '' :handleCreateSlots(values)}} // Call the function when the button is clicked
                                              className="flex w-100 h-100 Apply origin-center text-white text-sm font-semibold font-['Poppins'] items-center	ButtonsPrimaryDisabled mt-3 origin-center self-stretch bg-red-400 rounded-2xl  border flex-col justify-center items-center flex" style={{ color: "white", minHeight: "2.5rem", width: "100%", border: "1px solid #F1735F" }}
                                            >Save</button>
                                            {/* </div> */}
                                          </Form>
                                        )}
                                      </Formik>
                                    </>
                                  }

                                  {!isSaveBtn && !slotEditMode &&
                                    // <div
                                    //   className="ButtonsPrimaryDisabled origin-center self-stretch min-h-15 h-15 -rotate-180 rounded-2xl border flex-col justify-center items-center flex"
                                    //   style={{
                                    //     minHeight: "2.5rem",
                                    //     border: "1px solid #F1735F",
                                    //   }}
                                    // >
                                    <button
                                      type="button"
                                      onClick={() => handleAddslotClick()}
                                      className="flex w-100 h-100 Apply text-white text-sm font-semibold font-['Poppins'] items-center ButtonsPrimaryDisabled origin-center self-stretch rounded-2xl border justify-center"
                                      style={{ color: "#F1735F", minHeight: "2.5rem", border: "1px solid #F1735F", }}
                                    >
                                      Add Slot
                                      <img
                                        src="/images/plusorange.png"
                                        alt="plus"
                                        className="ml-2"
                                        style={{ color: "#F1735F" }}
                                      />
                                    </button>


                                    // </div>
                                  }

                                </div>
                                <div className="Section flex-col justify-start items-start gap-5 flex">
                                  {currTabName == "Tour" && (
                                    <div className="TourSchedule1 mt-3 w-56 text-slate-900 text-sm font-semibold font-['Poppins-Regular'] leading-tight">
                                      Location
                                    </div>
                                  )}

                                  <EventMode eventType={eventType} setEventType={setEventType} />
                                </div>
                                {eventType === "ON CAMPUS" ?
                                  // edit Gmap
                                  <OnCampusEventAndTour schools={schools} setSchoolLocation={setSchoolLocation} setLat={setLat} setLng={setLng} Lat={Lat} Lng={Lng} googleMapPin={googleMapPin} event_location={eventTourEditData?.location} />
                                  :
                                  <div className={`InputsBasicInputFull ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex`}>
                                    <div className="col-span-2 w-full">
                                      <label className="labels-children">MEETING LINK</label>
                                      <MyTextInput className="children-inputs" name="meeting_url" type="text" required={true} placeholder="Address Here" />
                                    </div>
                                  </div>
                                }
                                {currTabName === "Tour" && <div style={{ marginTop: eventType === "ON CAMPUS" ? "190px" : "0px" }}>
                                  {/* <div className="TourSchedule1 mt-3 w-56 text-slate-900 text-sm font-semibold font-['Poppins-Regular']" >
                                    Other
                                  </div> */}
                                  {/* <div className={`Checkboxes1 ${isMobile ? 'w-full' : 'w-96'} justify-start items-start inline-flex `}>
                                    <div class=" flex" >
                                    <label class="flex items-center ">
                                        <input type="radio" onClick={() => setOtherType("Group Tour")} class="form-radio square-radio" name="tour_type" value="option2" checked={otherType == "Group Tour" && true} />
                                        <span class="ml-2">Group Tour</span>
                                      </label>
                                      <label class="flex items-center ml-4">
                                        <input onClick={() => setOtherType("Individual")} type="radio" class=" form-radio square-radio" name="tour_type" value="option1" checked={otherType == "Individual" && true} />
                                        <span class="ml-2">Individual</span>
                                      </label>
                                      
                                    </div>
                                  </div> */}
                                </div>}
                                <div className={`InputsBasicInputFull12 ${isMobile ? 'w-full' : 'w-96'} h-12 flex-col justify-end items-start flex space-x-3`} style={{ marginTop: eventType === "ON CAMPUS" && currTab !== "tour" ? "17rem" : "4rem" }}>
                                  <div class="w-full">
                                    <label className="labels">DESRIPTION</label>
                                    <textarea
                                      value={description}
                                      onChange={(e) => setDescription(e.target.value)}
                                      className="input-textarea"
                                      // label="ADDRESS"
                                      name="description"
                                      maxLength={200}
                                      type="textarea"
                                      rows={4}
                                      placeholder="Short BIO"
                                    ></textarea>
                                    <p className="get-text-area-comment flex justify-end">
                                      {description?.length > 0 ? description?.length : 0}/200
                                    </p>
                                  </div>
                                </div>
                                <div className="Buttons self-stretch justify-start items-start gap-5 inline-flex">
                                  <div className="w-full flex flex-row space-x-3">
                                    <button
                                      type="button"
                                      color="primary"
                                      className="button w-full align-middle ixnline-flex items-center border delete-btn"
                                      style={{  border: "1px solid #F1735F", width:'100%'}}
                                      onClick={(e) => {
                                        setConfirmLbl("Yes, cancel")
                                        setCancelLbl("No")
                                        setModalMessage(`Are you sure you want to cancel ${eventTourEditData?.name ? eventTourEditData?.name : slotNamesString} ${currTabName == "Tour" ? "Tour" : "Event"}?`)
                                        setConfirmModel(true)
                                      }}
                                    >
                                   <span style={{ display: "flex", fontSize: "12px" , 
                                    flexDirection: "row", fontWeight:600 , }}> Cancel {currTabName}  <img
                                        src="/images/delete2.svg"
                                        className="h-4 w-4  text-gray-700 ml-2 "
                                      /></span>
                                    </button>
                                  </div>
                                  <div className="w-full flex flex-row space-x-3">
                                    <button
                                      type="submit" color="primary" className="button button-default" style={{ minHeight: "2.5rem", border: "1px solid #F1735F", }}
                                    // onClick={() => {
                                    //   setModalMessage(`${currTabName == "Tour" ? "Tour" : "Event"} edited successfully!!`)
                                    //   setConfirmModel(true)
                                    // }}
                                    >
                                      Update
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Form>
                    )}
                  </Formik>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition.Root>
    </div >
    </>
  );
};

export default SchoolTabsSection;
Editor is loading...
Leave a Comment