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

import {
  getViewersCounterAction,
  updateLiveEventFormAction,
  updateViewersCounterStatusAction,
} from '../../../../redux/slices';
import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { displayViewersCounterSelector, viewersAmountSelector } from '@/modules/liveEvents/liveEvent/redux/selectors';

import { FormRow, useFormSettings } from '@/modules/@common/Form';
import useIsAllowedToCreateOrEdit from '@/modules/liveEvents/liveEvent/hooks/useIsAllowedToCreateOrEdit';
import { FormControlLabel, Switch } from '@/mui/components';

const formatViewersCount = (viewers) => (typeof viewers === 'number' ? abbreviateNumber(viewers) : 'N/A');

function ViewersCounter() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const isAllowedToCreateOrEdit = useIsAllowedToCreateOrEdit();
  const displayViewersCounter = useSelector(displayViewersCounterSelector);
  const viewersAmount = useSelector(viewersAmountSelector);

  useEffect(() => {
    dispatch(getViewersCounterAction());

    const getViewersInterval = setInterval(() => dispatch(getViewersCounterAction()), 60000);

    return () => {
      clearInterval(getViewersInterval);
    };
  }, []);

  return (
    <FormRow label={`Live viewers: ${formatViewersCount(viewersAmount)}`}>
      <FormControlLabel
        labelPlacement="end"
        control={
          <Switch
            size={size}
            checked={displayViewersCounter}
            data-id="displayViewersCounter"
            color="primary"
            disabled={!isAllowedToCreateOrEdit}
            onChange={() => {
              dispatch(
                updateLiveEventFormAction({
                  displayViewersCounter: !displayViewersCounter,
                }),
              );
              dispatch(updateViewersCounterStatusAction());
            }}
          />
        }
        label="Display on Player"
      />
    </FormRow>
  );
}

export default ViewersCounter;
