import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { InfoOutlined } from '@mui/icons-material';

import { ASPECT_RATIOS, EMBED_CODE_TYPES } from '@/modules/@common/EmbedCodePopup/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { getIsWPVideoMode } from '@/modules/@common/app/helpers';
import copyToClipboard from '@/modules/@common/helpers/copy';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  MenuItem,
  Select,
  Stack,
  Switch,
  Tooltip,
  Typography,
} from '@/mui/components';

import styles from './EmbedCodePopup.module.scss';

type PlayerType = {
  label: string;
  value: string | number;
};

type AspectRatioType = {
  value: string;
};

type EmbedCodeType = {
  value: string;
};

type Props = {
  embedCode: string;
  handleAspectRatioChange: (aspectRatio: AspectRatioType | undefined) => void;
  handleEmbedCodeTypeChange: (embedCodeType: EmbedCodeType | undefined) => void;
  handlePlayerChange: (player: PlayerType | undefined) => void;
  isAspectRatioDisabled?: boolean;
  isCopyDisabled?: boolean;
  isPlayerDisabled?: boolean;
  isInProcessing?: boolean;
  onClose: () => void;
  players: PlayerType[];
  selectedAspectRatio?: AspectRatioType;
  selectedEmbedCodeType?: EmbedCodeType;
  selectedPlayer?: PlayerType;
  title?: string;
  thumbnail?: string;
  showAspectRatio?: boolean;
  showEmbedCodeTypes?: boolean;
  showVideoObjectSwitch?: boolean;
  videoObjectChecked?: boolean;
  videoObjectOnChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  disableVideoObjectSwitch?: boolean;
};

function EmbedCodePopup({
  onClose,
  embedCode = '',
  handleAspectRatioChange = () => {},
  handleEmbedCodeTypeChange = () => {},
  handlePlayerChange = () => {},
  isAspectRatioDisabled = false,
  isCopyDisabled = false,
  isPlayerDisabled = false,
  title = 'Video Embed Code',
  isInProcessing = false,
  thumbnail = '',
  players = [],
  selectedPlayer,
  selectedAspectRatio = ASPECT_RATIOS[0],
  selectedEmbedCodeType = EMBED_CODE_TYPES[0],
  showAspectRatio = true,
  showEmbedCodeTypes = false,
  showVideoObjectSwitch = false,
  videoObjectChecked = false,
  videoObjectOnChange = () => {},
  disableVideoObjectSwitch = false,
}: Props) {
  const [isWPVideoMode, setIsWPVideoMode] = useState(false);

  useEffect(() => {
    setIsWPVideoMode(getIsWPVideoMode());
  }, []);

  const dispatch = useDispatch();

  const aspectRatio = ASPECT_RATIOS.find(({ value }) => value === selectedAspectRatio?.value)?.value ?? '';

  const embedCodeType = EMBED_CODE_TYPES.find(({ value }) => value === selectedEmbedCodeType?.value)?.value ?? '';

  const handleCopySourceCode = () => {
    copyToClipboard(embedCode).then(() => {
      dispatch(
        showNotificationAction({
          type: TYPE_SUCCESS,
          message: 'Embed code copied to clipboard',
        }),
      );
    });
    onClose();
  };

  const handleSendMessage = () => {
    const data = {
      type: 'ac_editorial_message',
      embed: {
        displayEmbedCode: true,
        embedCode,
      },
      thumbnail,
    };
    window.parent.postMessage(data, '*');
  };

  return (
    <Dialog
      maxWidth="xl"
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      open
      onClose={onClose}
    >
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <Stack spacing={4}>
          {(!!players.length || showAspectRatio || showVideoObjectSwitch || showEmbedCodeTypes) && (
            <Stack direction="row" spacing={4} alignItems="center" justifyContent="space-between">
              {!!players.length && (
                <Select
                  data-id="select-players"
                  value={selectedPlayer?.value ?? 'text'}
                  className={styles.Input}
                  onChange={({ target }) => {
                    const player$ = players.find((item) => item.value === target.value);

                    handlePlayerChange(player$);
                  }}
                  // placeholder="Select Player"
                  disabled={isPlayerDisabled}
                >
                  {players.map(({ label, value }) => (
                    <MenuItem key={value} value={value}>
                      {label}
                    </MenuItem>
                  ))}
                </Select>
              )}
              {showAspectRatio && (
                <Select
                  data-id="select-aspect-ratio"
                  value={aspectRatio}
                  className={styles.Input}
                  disabled={isAspectRatioDisabled}
                  onChange={({ target }) => {
                    const aspectRation$ = ASPECT_RATIOS.find((item) => item.value === target.value);

                    handleAspectRatioChange(aspectRation$);
                  }}
                  // placeholder="Select Aspect Ratio"
                >
                  {ASPECT_RATIOS.map(({ label, value }) => (
                    <MenuItem key={value} value={value}>
                      {label}
                    </MenuItem>
                  ))}
                </Select>
              )}
              {showEmbedCodeTypes && (
                <Select
                  data-id="select-embed-code-type"
                  value={embedCodeType}
                  className={styles.Input}
                  disabled={!showEmbedCodeTypes}
                  onChange={({ target }) => {
                    const embedCodeType$ = EMBED_CODE_TYPES.find((item) => item.value === target.value);

                    handleEmbedCodeTypeChange(embedCodeType$);
                  }}
                  // placeholder="Select Embed Code Type"
                >
                  {EMBED_CODE_TYPES.map(({ label, value }) => (
                    <MenuItem key={value} value={value}>
                      {label}
                    </MenuItem>
                  ))}
                </Select>
              )}
              {showVideoObjectSwitch && (
                <Stack spacing={2} direction="row" alignItems="center">
                  <FormControlLabel
                    control={
                      <Switch
                        checked={videoObjectChecked}
                        onChange={videoObjectOnChange}
                        name="videoObject"
                        color="primary"
                        disabled={isInProcessing || disableVideoObjectSwitch}
                      />
                    }
                    labelPlacement="start"
                    label="Include&nbsp;SEO"
                  />
                  <Tooltip
                    title="Automatically add video metadata as SEO markup.
                  Search engines will be able to use this information to index and show your video in search result"
                    placement="top-end"
                  >
                    <InfoOutlined fontSize="medium" htmlColor="info.main" />
                  </Tooltip>
                </Stack>
              )}
            </Stack>
          )}
          {!isWPVideoMode && (
            <Stack spacing={2}>
              <Typography variant="subtitle2" color="text.secondary">
                Copy Embed Code into Your CMS
              </Typography>
              <Typography variant="body2" component="div" className={styles.Code}>
                {embedCode}
              </Typography>
              {isInProcessing && (
                <>
                  <Typography variant="caption" color="error.main">
                    Processing video. It will be available for playback in a few minutes
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    You may use the embed code, the video will play on page once processing is completed
                  </Typography>
                </>
              )}
            </Stack>
          )}
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button size="small" variant="outlined" onClick={onClose}>
          Cancel
        </Button>
        <Button
          size="small"
          variant="contained"
          onClick={isWPVideoMode ? handleSendMessage : handleCopySourceCode}
          disabled={!isWPVideoMode && isCopyDisabled}
        >
          {isWPVideoMode ? 'Insert Into Post' : 'Copy'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default EmbedCodePopup;
