import React, {
  Fragment,
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import "./FilterSlider.styles.scss";
import KeyboardArrowLeftIcon from "@mui/icons-material/KeyboardArrowLeft";
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
import ChevronRightOutlinedIcon from "@mui/icons-material/ChevronRightOutlined";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import PortalDropDown from "./Portal";

export default function FilterSlider({
  list,
  width,
  isExpanded = true,
  handleExpandClick,
  tagsChildren,
  containerChildren,
  setShowSeparator,
  onNextClick,
  onPrevClick,
  currDropShow,
  handleClickOutside = () => {},
}) {
  const [overFlow, setOverFlow] = useState(false);
  const [currCount, setCurrCount] = useState(0);
  const [translateX, setTranslateX] = useState(0);
  const [maxTranslateX, setMaxTranslateX] = useState(0);
  const [dropdownPosition, setDropdownPosition] = useState({
    x: 0,
    y: 0,
    width: 200,
  });
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);
  const tagContainer = useRef(null);
  const filtersContainer = useRef([]);
  const prevItemWidth = useRef(0);
  const prevCount = useRef(currCount);
  const memoizedHandleClickOutside = useCallback(handleClickOutside, []);

  const handleCloseClick = () => {
    setCurrCount(0);
    setTranslateX(0);
    if (handleExpandClick) handleExpandClick();
  };
  useLayoutEffect(() => {
    if (tagContainer.current) {
      const container = tagContainer.current;
      setOverFlow(container.scrollWidth > container.clientWidth);
      if (setShowSeparator) {
        setShowSeparator(container.scrollWidth > container.clientWidth);
      }
    }
  }, [tagContainer, list]);

  useLayoutEffect(() => {
    const container = tagContainer.current;
    if (!container) return;

    const checkScroll = () => {
      const maxScroll = container.scrollWidth - container.clientWidth;
      const currentScroll = container.scrollLeft;
      setCanScrollLeft(currentScroll > 0);
      setCanScrollRight(currentScroll < maxScroll - 1); // margin for precision
      setOverFlow(maxScroll > 0);
      if (setShowSeparator) setShowSeparator(maxScroll > 0);
    };

    // Run once immediately
    requestAnimationFrame(checkScroll);

    // Hook scroll + resize
    container.addEventListener("scroll", checkScroll);
    const resizeObserver = new ResizeObserver(checkScroll);
    resizeObserver.observe(container);

    return () => {
      container.removeEventListener("scroll", checkScroll);
      resizeObserver.disconnect();
    };
  }, [list, setShowSeparator]);

  useLayoutEffect(() => {
    if (filtersContainer.current[currCount]) {
      const itemWidth = filtersContainer.current[currCount].offsetWidth;
      let newTranslateX = translateX;

      if (currCount > prevCount.current) {
        newTranslateX += itemWidth;
      } else if (currCount < prevCount.current) {
        newTranslateX -= prevItemWidth.current;
      }

      newTranslateX = Math.min(newTranslateX, maxTranslateX);
      newTranslateX = Math.max(newTranslateX, 0);

      setTranslateX(newTranslateX);
      prevItemWidth.current = itemWidth;
      prevCount.current = currCount;
    }
  }, [currCount, maxTranslateX]);

  useEffect(() => {
    const handleMouseDown = (event) => {
      memoizedHandleClickOutside(event);
    };
    document.addEventListener("mousedown", handleMouseDown);
    return () => {
      document.removeEventListener("mousedown", handleMouseDown);
    };
  }, [memoizedHandleClickOutside]);

  const scrollAmount = 200; // or calculate based on tag average

  const handleNextClick = () => {
    if (onNextClick) onNextClick();
    if (!tagContainer.current) return;
    tagContainer.current.scrollBy({ left: scrollAmount, behavior: "smooth" });
  };

  const handlePrevClick = () => {
    if (onPrevClick) onPrevClick();
    if (!tagContainer.current) return;
    tagContainer.current.scrollBy({ left: -scrollAmount, behavior: "smooth" });
  };

  const handleTagClick = (index) => {
    if (filtersContainer.current[index]) {
      const rect = filtersContainer.current[index].getBoundingClientRect();
      setDropdownPosition({
        x: rect.right + window.scrollX,
        y: rect.bottom + window.scrollY,
        width: rect.width,
      });
    }
  };

  if (!Array.isArray(list)) return null;
  return (
    <div
      className="impact-selected-filter-container"
      style={{ width: width ? width : "100%" }}
    >
      <div
        className={`impact-selected-filter-tags ${!isExpanded && "collapsed"}`}
        ref={tagContainer}
      >
        {Array.isArray(list) &&
          list.map((item, index) => {
            return (
              <div
                className="impact-selected-filter-wrapper"
                key={item.id}
                style={{
                  transform: `translateX(-${translateX}px)`,
                }}
                ref={(el) => {
                  if (el) {
                    filtersContainer.current[index] = el; // Dynamically assign each ref
                  }
                }}
                onClick={() => handleTagClick(index)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    handleTagClick(index);
                  }
                  if (e.key === "Escape") {
                    handleClickOutside();
                  }
                }}
              >
                {containerChildren ? containerChildren(item, index) : null}
                <div className="impact-selected-filter-tags-container">
                  {tagsChildren ? tagsChildren(item, index) : null}
                </div>
                {currDropShow === index && (
                  <PortalDropDown
                    tags={item?.values.slice(2, 5)}
                    filtersContainer={filtersContainer}
                    index={index}
                    showButton={item.values.length > 6}
                    tag={item}
                    viewAllAction={item.handleViewAll}
                    position={dropdownPosition}
                  />
                )}
              </div>
            );
          })}
      </div>
      {overFlow && list.length > 2 ? (
        <div className="impact-selected-filter-action-btns">
          {isExpanded ? (
            <Fragment>
              <div
                className="impact-selected-filter-action-btn prev"
                role="button"
                style={{ opacity: canScrollLeft ? 1 : 0.5, pointerEvents: canScrollLeft ? "auto" : "none" }}
                onClick={handlePrevClick}
                tabIndex={canScrollLeft ? 0 : -1}
                aria-label="Previous filter"
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    handlePrevClick();
                  }
                }}
              >
                <KeyboardArrowLeftIcon />
              </div>
              <div
                className="impact-selected-filter-action-btn next"
                role="button"
                style={{ opacity: canScrollRight ? 1 : 0.5, pointerEvents: canScrollRight ? "auto" : "none" }}
                onClick={handleNextClick}
                tabIndex={canScrollRight ? 0 : -1}
                aria-label="Next filter"
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    handleNextClick();
                  }
                }}
              >
                <KeyboardArrowRightIcon />
              </div>
              {handleExpandClick && (
                <div
                  className="impact-selected-filter-action-btn next"
                  role="button"
                  style={{ opacity: currCount === list.length ? "0.5" : 1 }}
                  onClick={handleCloseClick}
                  tabIndex={0}
                  aria-label="Close filter"
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      handleCloseClick();
                    }
                  }}
                >
                  <CloseOutlinedIcon fontSize="small" />
                </div>
              )}
            </Fragment>
          ) : (
            <div
              className="impact-selected-filter-action-btn expand"
              role="button"
              style={{ opacity: currCount === list.length ? "0.5" : 1 }}
              onClick={handleExpandClick}
              tabIndex={0}
              aria-label="Expand filter"
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  handleExpandClick();
                }
              }}
            >
              <p>{"+" + list.length}</p> <ChevronRightOutlinedIcon />
            </div>
          )}
        </div>
      ) : null}
    </div>
  );
}
