import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { InfoOutlined } from '@mui/icons-material';

import {
  ASPECT_RATIO,
  EVENT_STATUS_ARCHIVED,
  EVENT_UX_TYPES_IMAGE,
  EVENT_UX_TYPES_SAME,
  MAX_FIELD_INPUT_SIZE,
  POST_EVENT,
  PRE_EVENT,
} from '../../constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import {
  countdownSelector,
  eventStatusSelector,
  playerAspectRatioSelector,
  playerIdSelector,
  postEventImagesSelector,
  postEventTextSelector,
  postEventTypeSelector,
  preEventImagesSelector,
  preEventTextSelector,
  preEventTypeSelector,
  transitionTextSelector,
} from '../../redux/selectors';
import { getLiveEventDefaultImagesAction, uploadLiveEventImageFlowAction } from '../../redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import { FormImageUploader, FormRow, useFormSettings } from '@/modules/@common/Form';
import useIsAllowedToCreateOrEdit from '../../hooks/useIsAllowedToCreateOrEdit';
import { Checkbox, FormControlLabel, MenuItem, Select, Stack, TextField, Tooltip, Typography } from '@/mui/components';

import noImage from '@/assets/img/no-image-portrait.svg';

function EventPrePost(props) {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const inputPreThumbRef = useRef(undefined);
  const inputPostThumbRef = useRef(undefined);
  const isAllowedToCreateOrEdit = useIsAllowedToCreateOrEdit();
  const preEventText = useSelector(preEventTextSelector);
  const countdown = useSelector(countdownSelector);
  const preEventType = useSelector(preEventTypeSelector);
  const preEventImages = useSelector(preEventImagesSelector);
  const postEventImages = useSelector(postEventImagesSelector);
  const postEventText = useSelector(postEventTextSelector);
  const postEventType = useSelector(postEventTypeSelector);
  const transitionText = useSelector(transitionTextSelector);
  const playerId = useSelector(playerIdSelector);
  const playerAspectRatio = useSelector(playerAspectRatioSelector);
  const eventStatus = useSelector(eventStatusSelector);

  const isArchived = eventStatus === EVENT_STATUS_ARCHIVED;

  const handleImageUpload = (image, type) => {
    dispatch(
      uploadLiveEventImageFlowAction({
        type,
        image,
      }),
    );

    if (inputPreThumbRef.current) {
      inputPreThumbRef.current.value = '';
    }
    if (inputPostThumbRef.current) {
      inputPostThumbRef.current.value = '';
    }
  };

  useEffect(() => {
    if (playerId && playerAspectRatio && !preEventImages?.length) {
      const imagesAspectRatio = ASPECT_RATIO[playerAspectRatio];
      dispatch(
        getLiveEventDefaultImagesAction({
          eventType: PRE_EVENT,
          aspectRatio: imagesAspectRatio,
        }),
      );
    }
  }, [playerId, preEventImages, playerAspectRatio]);

  const handleAddImage = (eventType) => {
    const imagesAspectRatio = ASPECT_RATIO[playerAspectRatio];
    dispatch(
      getLiveEventDefaultImagesAction({
        eventType,
        aspectRatio: imagesAspectRatio,
      }),
    );
  };

  const onValidate = (file) => {
    const maxSize = 2 * 100 * 1000; // 2 Mb
    const allowedExtensions = ['jpg', 'jpeg', 'png'];

    const extension = file.name.split('.').pop();

    if (!allowedExtensions.some((ext) => ext === extension)) {
      dispatch(
        showNotificationAction({
          type: TYPE_ERROR,
          message: `Invalid file extension, valid only (${allowedExtensions.join(',')})`,
        }),
      );

      return false;
    }

    if (file.size > maxSize) {
      dispatch(
        showNotificationAction({
          type: TYPE_ERROR,
          message: 'File size exceeded the maximum size permitted',
        }),
      );
      return false;
    }

    return true;
  };

  return (
    <>
      <FormRow label="Pre-Event Text" multiline tooltip="Customize the text that appears before the event begins">
        <FormControlLabel
          control={
            <Checkbox
              size={size}
              disabled={!isAllowedToCreateOrEdit || isArchived}
              checked={countdown}
              data-id="liveEventCountdown"
              color="primary"
              onChange={() => props.handleOnChange('countdown', !countdown)}
            />
          }
          label={
            <Stack direction="row" spacing={2} alignItems="center">
              <Typography variant="body2">Show Countdown</Typography>
              <Tooltip title="Show a countdown until the live event start time">
                <InfoOutlined fontSize="small" htmlColor="info.main" />
              </Tooltip>
            </Stack>
          }
        />
        <TextField
          size={size}
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={preEventText}
          placeholder="Enter your text"
          onChange={(event) => props.handleOnChange('preEventText', event.target.value)}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
        />
      </FormRow>
      <FormRow label="Pre-Event Visuals" tooltip="Customize the  pre-event look-and-feel">
        <Select
          size={size}
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={preEventType}
          data-id="liveEventPreEventType"
          onChange={(event) => props.handleOnChange('preEventType', event.target.value)}
        >
          <MenuItem disabled={!playerId} value={EVENT_UX_TYPES_IMAGE}>
            Poster Image
          </MenuItem>
        </Select>
      </FormRow>
      {!!playerId && [EVENT_UX_TYPES_IMAGE].includes(preEventType) && (
        <FormRow label>
          <FormImageUploader
            accept=".jpg,.jpeg,.png"
            image={preEventImages?.length ? preEventImages[preEventImages.length - 1]?.file : noImage}
            disabled={!isAllowedToCreateOrEdit}
            readOnly={!isAllowedToCreateOrEdit}
            onValidate={onValidate}
            onLoad={(event, file) => handleImageUpload(file, PRE_EVENT)}
            onRemove={() => handleAddImage(PRE_EVENT)}
          />
        </FormRow>
      )}
      <FormRow label="Live Transition" tooltip="Customize the text that appears when the event is about to go live">
        <TextField
          size={size}
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={transitionText}
          placeholder="Enter your text"
          onChange={(e) => props.handleOnChange('transitionText', e.target.value)}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
        />
      </FormRow>
      <FormRow label="Post-Event Text" tooltip="Customize the text that appears after the event ends">
        <TextField
          size={size}
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={postEventText}
          placeholder="Live event Ended"
          onChange={(e) => props.handleOnChange('postEventText', e.target.value)}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
        />
      </FormRow>
      <FormRow label="Post-Event Visuals" tooltip="Customize the  post-event look-and-feel">
        <Select
          size={size}
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={postEventType}
          onChange={(event) => props.handleOnChange('postEventType', event.target.value)}
        >
          <MenuItem value={EVENT_UX_TYPES_SAME}>Same as Pre-Event</MenuItem>
          <MenuItem disabled={!playerId} value={EVENT_UX_TYPES_IMAGE}>
            Poster Image
          </MenuItem>
        </Select>
      </FormRow>
      {([EVENT_UX_TYPES_IMAGE].includes(postEventType) ||
        ([EVENT_UX_TYPES_IMAGE].includes(preEventType) && postEventType === EVENT_UX_TYPES_SAME)) &&
        !!playerId && (
          <FormRow label>
            <FormImageUploader
              accept=".jpg,.jpeg,.png"
              image={postEventImages?.length ? postEventImages[preEventImages.length - 1]?.file : noImage}
              readOnly={!isAllowedToCreateOrEdit || isArchived}
              disabled={!isAllowedToCreateOrEdit || isArchived || !(postEventType === EVENT_UX_TYPES_IMAGE)}
              onValidate={onValidate}
              onLoad={(event, file) => handleImageUpload(file, POST_EVENT)}
              onRemove={() => handleAddImage(POST_EVENT)}
            />
          </FormRow>
        )}
    </>
  );
}

EventPrePost.propTypes = {
  handleOnChange: PropTypes.func.isRequired,
};

export default EventPrePost;
