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

const ViewControllerModal = () => {
  // const { sliders } = parameters;
  const [offset, setOffset] = useState(1);
  const [isActive, setIsActive] = useState(false);
  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);
      setIsActive(false);
    }
    if (eventData.dir === "Up") {
      setOffset(0);
      setIsActive(true);
    }
  };

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

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

  const handleOnSwiping = (eventData: SwipeEventData) => {
    const screenHeight = window.innerHeight;
    if (eventData.dir === "Down" && isActive && offset <= 1) {
      const offsetDown = eventData.absY / screenHeight;
      setOffset(() => offsetDown);
    }
    if (eventData.dir === "Up" && !isActive && offset >= 0) {
      const offsetDown = 1 - eventData.absY / screenHeight;
      setOffset(() => offsetDown);
    }
  };

  const handlers = useSwipeable({
    onSwiped: handleOnSwiped,
    onSwiping: handleOnSwiping,

    preventScrollOnSwipe: offset !== 0,
    trackTouch: isTouchable,
  });

  return (
    <div className="flex flex-col fixed left-0 top-0 z-20" {...handlers}>
      <div
        className={`${
          isActive ? "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 />
          <Parameters />
          <ImageSlider />
          {/* <UnitList /> */}
        </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;
