import { FC, MouseEvent, useState } from 'react';
import { useFormContext } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { useLokaliseTranslation } from 'src/utils/i18n';

import FormTextField from 'src/components/FormInputs/FormTextField';
import {
  isYoutubeLink,
  getEmbedLink,
} from 'src/components/FormInputs/FormYoutubeVideo/utils';

export type FormYoutubeVideoProps = {
  name: string;
  disabled?: boolean;
  onClick?: (event: MouseEvent<HTMLButtonElement>) => void;
  showPreview?: boolean;
};

export const FormYoutubeVideo: FC<FormYoutubeVideoProps> = props => {
  const {
    name,
    disabled = false,
    onClick = () => null,
    showPreview = false,
  } = props;

  const { watch } = useFormContext();
  const { t } = useLokaliseTranslation('backoffice_only');

  const url = watch(name);
  const isValid = isYoutubeLink(url);

  const [showPreviewLink, setShowPreviewLink] = useState(
    showPreview && isValid,
  );

  const handleChangeUrl = () => {
    setShowPreviewLink(false);
  };

  const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
    onClick(event);
    if (isValid) {
      setShowPreviewLink(true);
    }
  };

  return (
    <Stack
      sx={{
        gap: 3,
      }}
    >
      <Stack
        sx={{
          gap: 3,
          flexDirection: 'row',
        }}
      >
        <FormTextField
          name={name}
          disabled={disabled}
          variant="outlined"
          label={t('backoffice_only:form_youtube_video.youtube_label')}
          placeholder={t(
            'backoffice_only:form_youtube_video.youtube_placeholder',
          )}
          onChange={handleChangeUrl}
        />
        <Button
          onClick={handleClick}
          disabled={disabled || !isValid}
          variant="contained"
          color="secondary"
          size="large"
          sx={{
            minWidth: '163px',
          }}
        >
          {t('backoffice_only:form_youtube_video.youtube_action')}
        </Button>
      </Stack>
      {showPreviewLink && (
        <Stack
          sx={{
            '& iframe': {
              width: '100%',
              borderRadius: '20px',
            },
          }}
        >
          <iframe
            width="822"
            height="230"
            src={getEmbedLink(url)}
            title={t('backoffice_only:form_youtube_video.youtube_player')}
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
          />
        </Stack>
      )}
    </Stack>
  );
};

export default FormYoutubeVideo;
