import React, {useState} from 'react';
import {Box} from "@mui/material";
import gradientList from "@/components/horizontal-bars-page-change/utils/gradient-list";

interface HorizontalBarsPageChangeProps {
  startColor: string;
  endColor?: string;
  numBars?: number;
  shown: boolean;
  onTransitionEnd: () => void;
  msDelay?: number;
  timeout?: number;
  msTransitionSpeed?: number;
}

const HorizontalBarsPageChange = ({
  startColor = "white",
  endColor,
  numBars = 7,
  shown,
  onTransitionEnd = () => {},
  msDelay = 100,
  timeout = 0,
  msTransitionSpeed = 500
}: HorizontalBarsPageChangeProps) => {

  const gradientArray = gradientList({startColor, endColor: endColor ?? startColor, numBars});
  const [isReflected, setIsReflected] = useState<boolean>(false);
  const handleTransitionEnd = () => {
    setTimeout(() => {
      setIsReflected((prev) => !prev);
      onTransitionEnd();
    }, timeout);
  };

  return (
    <Box
      sx={{
        position: "fixed",
        transform: isReflected ? "scaleX(-1)" : "scaleX(1)",
        top: 0,
        left: 0,
        width: "100vw",
        height: "100vh",
        zIndex: 9999,
        display: "flex",
        flexDirection: "column",
        pointerEvents: shown ? "auto" : "none", // Click-through when hidden
      }}
    >
      {gradientArray.map((color, i) => {
        return (
          <Box
            key={i}
            sx={{
              height: `${100 / gradientArray.length}%`,
              top: `${100 / gradientArray.length}%`,
              width: shown ? "100%" : 0 ,
              backgroundColor: color,
              transition: `width ${msTransitionSpeed}ms ease-${isReflected ? "in" : "out"}`,
              transitionDelay: `${msDelay * (isReflected ? gradientArray.length - i : i )}ms`
            }}
            onTransitionEnd={i === (isReflected
              ? 0
              : numBars - 1) ? handleTransitionEnd : () => {}}
          />
        )
      })}
    </Box>
  );
};

export default HorizontalBarsPageChange;