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

import {
  DEMAND_TAG_FREQUENCY_CAP_TIMEFRAME_LIST,
  DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST,
  DEMAND_TAG_FREQUENCY_TAB_STATUS,
} from '@/modules/marketplace/account/constants';

import * as selectors from '../../../../redux/selectors';
import * as actions from '../../../../redux/slices';
import { integerFieldBlockInvalidChar } from '@/modules/marketplace/account/helpers/validate';

import { Form, FormContent, FormGroup, FormRow, FormRowItem, FormSection } from '@/modules/@common/Form';
import {
  FormControlLabel,
  MenuItem,
  Select,
  Switch,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
} from '@/mui/components';

function FrequencyCapTab() {
  const dispatch = useDispatch();

  const frequencyCap = useSelector(selectors.frequencyCapSelector);
  const { status, type, value, timeframe, amount, prevSavedData } = frequencyCap;

  const pageConfig = useSelector(selectors.pageConfigSelector);

  const { isCreatingNew, isDuplicate } = pageConfig ?? {};

  const [isEnabled, setEnabled] = useState(DEMAND_TAG_FREQUENCY_TAB_STATUS.active === status);

  useEffect(() => {
    setEnabled(DEMAND_TAG_FREQUENCY_TAB_STATUS.active === status);
  }, [status]);

  const savePrevFrequencyCap = () => {
    if (!isCreatingNew && !isDuplicate && !prevSavedData) {
      dispatch(
        actions.setFrequencyCapTabAction({
          prevSavedData: {
            status,
            type,
            value,
            timeframe,
            amount,
          },
        }),
      );
    }
  };

  const handleChangeStatus = ({ target }) => {
    savePrevFrequencyCap();
    setEnabled(target.checked);
    dispatch(
      actions.setFrequencyCapTabAction({
        status: target.checked ? DEMAND_TAG_FREQUENCY_TAB_STATUS.active : DEMAND_TAG_FREQUENCY_TAB_STATUS.disabled,
      }),
    );
  };

  const handleSetAmount = ({ target }) => {
    savePrevFrequencyCap();
    dispatch(
      actions.setFrequencyCapTabAction({
        amount: +target.value > 0 ? +target.value : '',
      }),
    );
  };

  const handleSetFrequency = ({ target }) => {
    savePrevFrequencyCap();
    dispatch(actions.setFrequencyCapTabAction({ timeframe: target.value }));
  };

  const handleSetValue = ({ target }) => {
    savePrevFrequencyCap();
    dispatch(
      actions.setFrequencyCapTabAction({
        value: +target.value > 0 ? +target.value : '',
      }),
    );
  };

  const handleSetType = (typeParam) => {
    savePrevFrequencyCap();
    dispatch(
      actions.setFrequencyCapTabAction({
        type: typeParam,
      }),
    );
  };

  return (
    <Form>
      <FormContent>
        <FormSection>
          <FormRow
            label="Frequency Cap"
            tooltip="With automatic optimization per supply tag enabled, this frequency cap is used only as the initial value for new supply tags. Ongoing adjustments are managed automatically and not reflected here"
          >
            <FormControlLabel
              size="small"
              control={<Switch size="small" color="primary" checked={isEnabled} onChange={handleChangeStatus} />}
              labelPlacement="start"
            />
          </FormRow>
          {isEnabled && (
            <FormGroup>
              <FormRow label="Time Frame">
                <FormRowItem>Every</FormRowItem>
                <TextField
                  type="number"
                  value={amount}
                  size="small"
                  inputProps={{
                    min: '1',
                  }}
                  onKeyDown={integerFieldBlockInvalidChar}
                  onChange={handleSetAmount}
                />
                <Select
                  labelId="demo-simple-select-label"
                  value={timeframe}
                  variant="outlined"
                  size="small"
                  onChange={handleSetFrequency}
                >
                  {DEMAND_TAG_FREQUENCY_CAP_TIMEFRAME_LIST.map((item) => (
                    <MenuItem value={item.value} key={item.value}>
                      {item.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>
              <FormRow label="Type">
                <TextField
                  data-id="amountPerUser"
                  type="number"
                  value={value}
                  size="small"
                  inputProps={{
                    min: '1',
                  }}
                  onKeyDown={integerFieldBlockInvalidChar}
                  onChange={handleSetValue}
                />
                <ToggleButtonGroup equalWidth size="small" color="primary" variant="outlined" value={type}>
                  <ToggleButton
                    value={DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST.request}
                    onClick={() => handleSetType(DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST.request)}
                  >
                    Request
                  </ToggleButton>
                  <ToggleButton
                    value={DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST.impressions}
                    onClick={() => handleSetType(DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST.impressions)}
                  >
                    Impressions
                  </ToggleButton>
                </ToggleButtonGroup>
              </FormRow>
            </FormGroup>
          )}
        </FormSection>
      </FormContent>
    </Form>
  );
}

export default FrequencyCapTab;
