import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { useTheme } from '@mui/material/styles';

import {
  ASPECT_RATIO,
  EVENT_STATUS_ARCHIVED,
  MAX_FIELD_INDICATOR_TEXT,
  MAX_FIELD_INPUT_SIZE,
  PRE_EVENT,
} from '../../constants';

import {
  descriptionSelector,
  errorsSelector,
  eventStatusSelector,
  guidSelector,
  indicationColorSelector,
  indicationTextSelector,
  nameSelector,
  playerAspectRatioSelector,
  playerIdSelector,
  playersSelector,
  preEventImagesSelector,
  publisherIdSelector,
  publisherSelector,
  publishersSelector,
} from '../../redux/selectors';
import { getLiveEventDefaultImagesAction, getPublishersAction, updateLiveEventFormAction } from '../../redux/slices';

import { FormRow, FormRowItem, useFormSettings } from '@/modules/@common/Form';
import useIsAllowedToCreateOrEdit from '../../hooks/useIsAllowedToCreateOrEdit';
import {
  Autocomplete,
  ButtonColorPicker,
  Chip,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  TextField,
} from '@/mui/components';

function EventSetting(props) {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const router = useRouter();
  const name = useSelector(nameSelector);
  const description = useSelector(descriptionSelector);
  const indicationText = useSelector(indicationTextSelector);
  const indicationColor = useSelector(indicationColorSelector);
  const publishers = useSelector(publishersSelector);
  const publisher = useSelector(publisherSelector);
  const publisherId = useSelector(publisherIdSelector);
  const playerId = useSelector(playerIdSelector);
  const players = useSelector(playersSelector);
  const playerAspectRatio = useSelector(playerAspectRatioSelector);
  const guid = useSelector(guidSelector);
  const errors = useSelector(errorsSelector);
  const preEventImages = useSelector(preEventImagesSelector);
  const eventStatus = useSelector(eventStatusSelector);

  const { id } = router.query;
  const existedEventId = parseInt(id, 10);

  const theme = useTheme();

  const isArchived = eventStatus === EVENT_STATUS_ARCHIVED;

  const isAllowedToCreateOrEdit = useIsAllowedToCreateOrEdit();

  useEffect(() => {
    dispatch(getPublishersAction());
  }, []);

  useEffect(() => {
    if (playerId) {
      const player = players.find((item) => item.id === playerId);
      dispatch(
        updateLiveEventFormAction({
          player,
          playerAspectRatio: player?.playerAspectRatio,
        }),
      );
    }

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

  return (
    <>
      <FormRow label="Name">
        <TextField
          disabled={!isAllowedToCreateOrEdit || isArchived}
          error={errors.name && !errors.name?.isValid}
          variant="outlined"
          label="Required"
          required
          value={name}
          size={size}
          placeholder="Add name"
          onChange={(e) => props.handleOnChange('name', e.target.value)}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
        />
      </FormRow>
      <FormRow label="Description">
        <TextField
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={description}
          size={size}
          placeholder="Add description"
          onChange={(e) => props.handleOnChange('description', e.target.value)}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
        />
      </FormRow>
      <FormRow
        label="Live Indication"
        tooltip="Live event visual indicator - you can customize this field text and color"
        multiline
      >
        <FormRowItem itemsInRow={2}>
          <TextField
            disabled={!isAllowedToCreateOrEdit || isArchived}
            size={size}
            value={indicationText}
            placeholder="Live"
            onChange={({ target }) => {
              const { value } = target;
              if (value.length <= MAX_FIELD_INDICATOR_TEXT) {
                props.handleOnChange('indicationText', value);
              }
            }}
            inputProps={{
              maxlength: MAX_FIELD_INDICATOR_TEXT,
            }}
          />
        </FormRowItem>
        <Stack fullWidth />
        <FormRowItem itemsInRow={2}>
          <Stack spacing={2} fullWidth direction="row" alignItems="center" justifyContent="flex-start">
            <Chip
              // eslint-disable-next-line react/prop-types
              size={props.size}
              style={{
                backgroundColor: indicationColor,
                color: theme.palette.getContrastText(indicationColor),
              }}
              label={indicationText}
              shape="rounded"
            />
            <ButtonColorPicker
              size={size}
              color={indicationColor}
              disabled={!isAllowedToCreateOrEdit || isArchived}
              disableAlpha
              onPickerChange={({ hex }) => props.handleOnChange('indicationColor', hex)}
            />
          </Stack>
        </FormRowItem>
      </FormRow>
      {!existedEventId && (
        <FormRow label="Hub" tooltip="If you have multiple hubs, select the one that will be hosting the live event">
          <Autocomplete
            disabled={!isAllowedToCreateOrEdit || isArchived}
            id="publisher"
            size={size}
            optionLabelKey="name"
            optionValueKey="id"
            value={publishers?.find((pub) => pub.id === publisherId) || publisher}
            options={publishers}
            onOpen={() => dispatch(getPublishersAction())}
            onChange={(_, newValue) => {
              props.handleOnChange('publisherId', newValue?.id);
              dispatch(
                updateLiveEventFormAction({
                  playerId: 0,
                }),
              );
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                placeholder="Select Hub"
                onChange={() => dispatch(getPublishersAction())}
                label="Required"
                required
              />
            )}
          />
        </FormRow>
      )}
      {!!publisherId && (
        <FormRow label="Player" multiline>
          <FormControl size={size} fullWidth>
            <InputLabel size={size} required>
              Required
            </InputLabel>
            <Select
              size={size}
              disabled={!isAllowedToCreateOrEdit || isArchived}
              error={errors.playerId && !errors.playerId?.isValid}
              helperText={errors.playerId?.message}
              label="Required"
              required
              placeholder="Select Player"
              value={+playerId}
              onChange={(event) => props.handleOnChange('playerId', event.target.value)}
            >
              <MenuItem value={0} disabled>
                Select Player
              </MenuItem>
              {players.map((item) => (
                <MenuItem key={item.id} value={+item.id}>
                  {item.alias}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <FormRowItem itemsInRow={2}>Aspect Ratio</FormRowItem>
          <FormRowItem itemsInRow={2}>
            <TextField
              size={size}
              disabled
              data-id="liveEventAspectRatio"
              value={playerAspectRatio?.replace('_', ':') ?? ''}
            />
          </FormRowItem>
        </FormRow>
      )}
      <FormRow label="GUID">
        <TextField
          disabled={!isAllowedToCreateOrEdit || isArchived}
          value={guid}
          placeholder="Add external identifier"
          size={size}
          inputProps={{
            maxlength: MAX_FIELD_INPUT_SIZE,
          }}
          onChange={(event) => props.handleOnChange('guid', event.target.value)}
        />
      </FormRow>
    </>
  );
}

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

export default EventSetting;
