import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { FORCE_POSTER_OPTIONS, SAME_AS_PRE_EVENT } from '../../../../constants/forcePoster';

import { forcePosterSelector, forcePosterTypeSelector } from '../../../../redux/selectors';
import { updateForcePosterStatusAction, updateLiveEventFormAction } from '../../../../redux/slices';

import { FormRow, useFormSettings } from '@/modules/@common/Form';
import useIsAllowedToCreateOrEdit from '../../../../hooks/useIsAllowedToCreateOrEdit';
import { MenuItem, Select, Switch } from '@/mui/components';

function ForcePoster() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const forcePoster = useSelector(forcePosterSelector);
  const forcePosterType = useSelector(forcePosterTypeSelector);

  const handleChangeForcePosterState = ({ target }) => {
    dispatch(
      updateLiveEventFormAction({
        forcePoster: target.checked,
        forcePosterType: target.checked ? SAME_AS_PRE_EVENT : null,
      }),
    );

    dispatch(updateForcePosterStatusAction());
  };

  const handleChangeForcePosterType = ({ target }) => {
    dispatch(
      updateLiveEventFormAction({
        forcePosterType: target.value,
      }),
    );

    dispatch(updateForcePosterStatusAction());
  };

  return (
    <FormRow
      fullWidth
      label="Force Poster"
      tooltip={
        'A poster image to display outside the schedule. It will override the stream.\n' +
        'The poster changing can take up to 60 seconds'
      }
    >
      <Switch
        size={size}
        color="primary"
        checked={forcePoster}
        disabled={!useIsAllowedToCreateOrEdit}
        onChange={handleChangeForcePosterState}
      />
      {forcePoster && (
        <Select
          size={size}
          value={forcePosterType}
          disabled={!useIsAllowedToCreateOrEdit}
          onChange={handleChangeForcePosterType}
        >
          {FORCE_POSTER_OPTIONS.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      )}
    </FormRow>
  );
}

export default ForcePoster;
