import { useEffect, useState } from "react";
import { SwipeEventData, useSwipeable } from "react-swipeable";
import ButtonSwipperIcon from "../../../icons/ButtonSwipperIcon";
import { Parameters as ParametersType } from "../../../types/appartment";
import Parameters from "./Parameters";
// import LayoutSlider from "./LayoutSlider";
// import LayoutSlider from "./ImageSlider";
import LayoutSlider from "./LayoutSlider";
import ImageSlider from "./ImageSlider";
import ViewToggle from "../../ViewToggle";

type ViewControllerModalProps = {
  parameters: ParametersType;
};

const ViewControllerModal = ({ parameters }: ViewControllerModalProps) => {
  const { sliders } = parameters;
  const [offset, setOffset] = useState(1);
  const [isTouchable, setIsTouchable] = useState(true);
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    if (offset === 1 || scrollY === 0) {
      setIsTouchable(true);
    } else {
      setIsTouchable(false);
    }
  }, [scrollY, offset]);

  const handleOnSwiped = (eventData: SwipeEventData) => {
    if (eventData.dir === "Down") {
      setOffset(1);
    }
    if (eventData.dir === "Up") {
      setOffset(0);
    }
  };

  const handleOnBackClick = () => {
    setOffset(1);
  };

  const handleOnScroll = (event: React.UIEvent<HTMLDivElement, UIEvent>) => {
    setScrollY(event.currentTarget.scrollTop);
  };

  const handlers = useSwipeable({
    onSwiped: handleOnSwiped,
    preventScrollOnSwipe: offset === 1,
    trackTouch: isTouchable,
  });

  return (
    <div className=" flex flex-col fixed left-0 top-0 z-20 bg-black">
      <div
        {...handlers}
        className={`${
          offset === 1 ? "rounded-ss-2xl rounded-se-2xl" : ""
        } bg-white w-full h-[calc(100vh)] border flex flex-col transition-all duration-500 fixed left-0 top-0 ease-in-out`}
        style={{
          transform: `translateY(calc(${offset * 80}vh))`,
        }}
      >
        <ViewToggle offset={offset} />
        <div className="mx-auto flex justify-center self-start w-full">
          <ButtonSwipperIcon />
        </div>
        <div
          className="h-[calc(100vh-110px)] overflow-y-scroll relative"
          onScroll={handleOnScroll}
        >
          <LayoutSlider sliders={sliders} />
          <Parameters parameters={parameters} />
          <ImageSlider parameters={parameters} />
        </div>
        <div className="px-6 py-4 mt-auto border">
          <button
            className="border flex w-full py-3 justify-center rounded-full"
            onClick={handleOnBackClick}
          >
            Back
          </button>
        </div>
      </div>
    </div>
  );
};

export default ViewControllerModal;
