import { SyntheticEvent, useCallback, useState } from 'react';
import { ASSETS_URL } from '../../consts/common';
import { useWindowEventListener } from '../../utils';
import {
  StyledBackdrop,
  StyledCloseIcon,
  StyledPopupWrapper,
  StyledYouTubePlayer,
  StyledYouTubePoster
} from './styles';
import { EmptyStateYoutubeProps } from './types';

export const EmptyStateYoutube = (props: EmptyStateYoutubeProps) => {
  const { imageProps, imageUrl, isOpen = false, onClose, onOpen, ...youTubeProps } = props;

  const [open, setOpen] = useState(isOpen);

  const handleClose = useCallback<NonNullable<EmptyStateYoutubeProps['onClose']>>(
    event => {
      onClose?.(event);
      setOpen(false);
    },
    [onClose]
  );

  const handleOpen = useCallback<NonNullable<EmptyStateYoutubeProps['onOpen']>>(
    event => {
      onOpen?.(event);
      setOpen(true);
    },
    [onOpen]
  );

  useWindowEventListener(['keydown'], event => {
    if (open && (event as KeyboardEvent)?.code === 'Escape')
      handleClose(event as unknown as SyntheticEvent);
  });

  return (
    <>
      <StyledYouTubePoster
        data-testid="youTubePoster"
        onClick={handleOpen}
        src={imageUrl}
        alt=""
        {...imageProps}
      />

      <StyledBackdrop
        data-testid="backdrop"
        onClick={handleClose}
        open={open}
        transitionDuration={0}
      >
        {open && (
          <StyledPopupWrapper data-testid="popupWrapper">
            <StyledYouTubePlayer
              {...youTubeProps}
              opts={{
                ...youTubeProps?.opts,
                playerVars: {
                  autoplay: 0,
                  playsinline: 1,
                  rel: 0,
                  ...youTubeProps?.opts?.playerVars
                }
              }}
            />
          </StyledPopupWrapper>
        )}
        <StyledCloseIcon size="xlarge" src={`${ASSETS_URL}/icons2/icon_close.svg`} />
      </StyledBackdrop>
    </>
  );
};
