import { useEffect, useState, useRef } from "react";
import gsap from "gsap";
import useStore from "../../../store/store";
import UnitList from "../../UnitList";
import LayoutSlider from "../../mobile/Appartment/LayoutSlider";
import { LayoutToggle } from "../../LayoutToggle";
import CrossButton from "../../CrossButton";

const LayoutModal = () => {
  const [currentView, setCurrentView] = useState(1);
  const { currentVilla, setModal } = useStore();
  const [currentUnits, setCurrentUnits] = useState(
    currentVilla?.groundFloorUnits
  );

  const modalRef = useRef(null);

  useEffect(() => {
    if (!modalRef) return;
    gsap.fromTo(
      modalRef.current,
      {
        left: "100vw",
        bottom: "100vh",
      },
      {
        left: 0,
        bottom: 0,
        duration: 0.3,
      }
    );
  }, []);

  useEffect(() => {
    if (currentVilla) {
      switch (currentView) {
        case 3:
          setCurrentUnits(currentVilla.parkingUnits);
          break;
        case 2:
          setCurrentUnits(currentVilla.firstFloorUnits);
          break;
        default:
          setCurrentUnits(currentVilla.groundFloorUnits);
          break;
      }
    }
  }, [currentView, currentVilla]);

  const handleOnCloseClick = () => {
    const onAnimationComplete = () => {
      const timeout = setTimeout(() => {
        setModal(null);
        clearTimeout(timeout);
      }, 200);
    };

    gsap.fromTo(
      modalRef.current,
      {
        left: 0,
        bottom: 0,
      },
      {
        left: "100vw",
        bottom: "100vh",
        duration: 0.5,
        onComplete: onAnimationComplete,
      }
    );
  };

  return (
    // <div className="min-w-screen w-screen z-20 flex flex-col absolute">
    <>
      <div
        className="relative left-[100vw] bottom-[100vh] bg-white h-screen "
        ref={modalRef}
      >
        <div className="flex">
          <div className="min-w-[440px] overflow-y-clip flex flex-col justify-center">
            {currentUnits && <UnitList units={currentUnits} />}
          </div>
          <div className="w-full flex flex-col p-8">
            <LayoutSlider
              currentView={currentView}
              setCurrentView={setCurrentView}
            />
            <LayoutToggle
              className="max-w-[340px] mx-auto"
              currentView={currentView}
              setCurrentView={setCurrentView}
            />
          </div>
        </div>
      </div>
      <div className="flex justify-between pt-8 pr-8 absolute z-20 left-0 top-0 w-full">
        <div />
        <CrossButton onClick={handleOnCloseClick} />
      </div>
      {/* </div>
  <></> */}
    </>
  );
};

export default LayoutModal;
