import { useEffect, useState } from 'react';
import { SmallItemCarousel, ExitIcon, ErrorItemCarousel } from './styles';
import Backdrop from '@mui/material/Backdrop';
import SmallCarousel from './SmallCarousel';
import { EmptyStateCarouselProps, NEXT } from './types';
import BigCarousel from './BigCarousel';
import { ASSETS_URL } from '../../consts/common';

export const EmptyStateCarousel = ({
  items,
  isSmall,
  fallBackImg,
  imgClickEvent,
  leftClickEvent,
  rightClickEvent,
  vidoStartEvent,
  className,
  width,
  isError
}: EmptyStateCarouselProps) => {
  const [open, setOpen] = useState(false);
  const [index, setIndex] = useState<number>(0);

  const handleClose = (e: { stopPropagation: () => void }) => {
    setIndex(0);
    setOpen(false);
  };

  const handleToggle = (i?: number) => {
    setIndex(i || 0);
    setOpen(!open);
  };

  const handleBigCarousel = (dir: string) => {
    if (dir === NEXT) {
      if (items[index + 1]) {
        setIndex(index + 1);
      } else setIndex(0);
    } else {
      if (index > 0) {
        setIndex(index - 1);
      } else setIndex(items.length - 1);
    }
  };
  useEffect(() => {
    const close = (e: KeyboardEvent) => {
      if (e.code === 'Escape') {
        setIndex(0);
        setOpen(false);
      }
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, []);

  return (
    <div>
      <Backdrop
        sx={{
          zIndex: theme => theme.zIndex.drawer + 1,
          opacity: '0.8 !important',
          backgroundColor: '#000000'
        }}
        transitionDuration={0}
        open={open}
        onClick={handleClose}
      >
        <ExitIcon size="xlarge" src={`${ASSETS_URL}/icons/icon_close.svg`} />
      </Backdrop>
      {items ? (
        <SmallCarousel
          width={width}
          className={className}
          isSmall={isSmall}
          leftClickEvent={leftClickEvent}
          rightClickEvent={rightClickEvent}
        >
          {items.map((item, i) => (
            <SmallItemCarousel
              isSmall={isSmall}
              onClick={() => {
                imgClickEvent();
                handleToggle(i);
              }}
              key={i}
              img={item.imgUrl}
            />
          ))}
        </SmallCarousel>
      ) : (
        <ErrorItemCarousel
          isSmall={isSmall}
          onClick={() => handleToggle()}
          img={isError ? fallBackImg : ''}
        />
      )}
      <BigCarousel
        vidoStartEvent={vidoStartEvent}
        leftClickEvent={leftClickEvent}
        rightClickEvent={rightClickEvent}
        isSmall={isSmall}
        open={open}
        handleBigCarousel={handleBigCarousel}
        index={index}
        items={items}
        fallBackImg={isError ? fallBackImg : ''}
      />
    </div>
  );
};
