import React, { useEffect, useRef, useState } from "react";
import styles from "./DatePicker.module.css";

const ITEM_HEIGHT = 40; // Height of each date item

interface DatePickerItemProps {
  data: string[];
  selectedValue: string;
  onSelect: (value: string) => void;
  unit: string;
}

function useIsMobile() {
  const [isMobile, setIsMobile] = useState<boolean>(false);

  useEffect(() => {
    setIsMobile(window.matchMedia("(max-width: 600px)").matches);
  }, []);

  return isMobile;
}

const DatePickerItem: React.FC<DatePickerItemProps> = ({
  data,
  selectedValue,
  onSelect,
  unit,
}) => {
  const isMobile = useIsMobile();
  const scrollRef = useRef<HTMLDivElement | null>(null);

  const [isMouseDown, setIsMouseDown] = useState<boolean>(false);

  const [touchY, setTouchY] = useState<number>(0);
  const [translateY, setTranslateY] = useState<number>(
    (data.indexOf(selectedValue) + (unit === "month" ? 12 : 0)) * -ITEM_HEIGHT
  );

  const handleTouchStart = (event: React.TouchEvent<HTMLDivElement>) => {
    setTouchY(event.touches[0].clientY);
  };

  const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
    setTouchY(event.clientY);
    setIsMouseDown(true);
  };

  const handleTouchMove = (event: React.TouchEvent<HTMLDivElement>) => {
    if (isMobile && touchY !== null) {
      const deltaY = event.touches[0].clientY - touchY;
      wheelScroll(deltaY);

      setTouchY(event.touches[0].clientY);
    }
  };

  const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
    if (!isMobile && touchY !== null && isMouseDown) {
      const deltaY = event.clientY - touchY;
      wheelScroll(deltaY);

      setTouchY(event.clientY);
    }
  };

  // useEffect(() => {
  //   setTranslateY(
  //     (data.indexOf(selectedValue) + (unit === "month" ? 12 : 0)) * -ITEM_HEIGHT
  //   );
  // }, [selectedValue, data, unit]);

  useEffect(() => {
    if (unit === "month") {
      if (
        data.indexOf(selectedValue) < 12 ||
        data.indexOf(selectedValue) > 23
      ) {
        setTranslateY((data.indexOf(selectedValue) + 12) * -ITEM_HEIGHT);
      }
    }
    if (unit === "day") {
      if (
        data.indexOf(selectedValue) < 31 ||
        data.indexOf(selectedValue) > 62
      ) {
        setTranslateY((data.indexOf(selectedValue) + 31) * -ITEM_HEIGHT);
      }
    }
  }, [unit, data, selectedValue]);

  const handleTouchEnd = () => {
    if (isMobile && scrollRef.current) {
      const selectedIndex = Math.round(-translateY / ITEM_HEIGHT);
      onSelect(data[selectedIndex]);

      // Limit the translateY to ensure it aligns with a valid item
      setTranslateY(-selectedIndex * ITEM_HEIGHT);
      setTouchY(0);
    }
  };

  const handleMouseEnd = () => {
    if (!isMobile && scrollRef.current) {
      const selectedIndex = Math.round(-translateY / ITEM_HEIGHT);
      onSelect(data[selectedIndex]);

      // Limit the translateY to ensure it aligns with a valid item
      setTranslateY(-selectedIndex * ITEM_HEIGHT);
      setTouchY(0);
    }
    setIsMouseDown(false);
  };

  const handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {
    const deltaY = event.deltaY > 0 ? ITEM_HEIGHT : -ITEM_HEIGHT;
    wheelScroll(-deltaY);
    const selectedIndex = Math.round(
      -translateY / ITEM_HEIGHT + (event.deltaY > 0 ? 1 : -1)
    );
    onSelect(data[selectedIndex]);
  };

  const wheelScroll = (deltaY: number) => {
    const newTranslateY = translateY + deltaY;

    // Calculate the maximum and minimum translateY values based on the data length
    const minTranslateY = -ITEM_HEIGHT * (data.length - 1);
    const maxTranslateY = 0;

    // Ensure the newTranslateY stays within the valid range
    if (newTranslateY < minTranslateY) {
      setTranslateY(minTranslateY);
    } else if (newTranslateY > maxTranslateY) {
      setTranslateY(maxTranslateY);
    } else {
      setTranslateY(newTranslateY);
    }
  };

  return (
    <div className={styles["date-picker-viewport"]}>
      <div className={styles["date-picker-wheel"]}>
        <div
          className={styles["date-picker-scroll"]}
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseEnd}
          onWheel={handleWheel}
          ref={scrollRef}
          style={{
            transform: `translateY(${translateY}px)`,
            // msTransform: `translateY(${translateY}px)`,
            WebkitTransform: `translateY(${translateY}px)`,
          }}
        >
          {data.map((item, index) => (
            <div
              className={`${styles["date-picker-item"]} ${
                item === selectedValue ? styles["selected"] : ""
              }`}
              key={`${unit}-${index}`}
            >
              {item}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default DatePickerItem;
