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

import {
  AUTOMATIC_OPTIMIZATION,
  AUTOMATIC_OPTIMIZATION_FREQUENCY,
  AUTOMATIC_OPTIMIZATION_KPI_DISPLAY,
  AUTOMATIC_OPTIMIZATION_KPI_VIDEO,
  AUTOMATIC_OPTIMIZATION_PERIOD,
  AUTOMATIC_OPTIMIZATION_TIERS,
  DEMAND_TAG_FORMAT,
} from '@/modules/marketplace/account/constants';

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

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

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

  const supply = useSelector(selectors.supplySelector);

  const { format } = supply;

  const automaticOptimization = useSelector(selectors.automaticOptimizationSelector);
  const { status, kpi, period, frequency, hbTiers, kpiGap, errors } = automaticOptimization;

  useEffect(() => {
    dispatch(
      actions.setAutomaticOptimizationTabAction({
        hbTiers:
          format === DEMAND_TAG_FORMAT.video
            ? AUTOMATIC_OPTIMIZATION_TIERS[1].value
            : AUTOMATIC_OPTIMIZATION_TIERS[0].value,
        kpiGap: format === DEMAND_TAG_FORMAT.video ? '45' : '60',
      }),
    );
  }, [format]);

  return (
    <Form>
      <FormContent>
        <FormSection>
          <FormRow label="Automatic Optimization">
            <Switch
              color="primary"
              size="small"
              checked={status === AUTOMATIC_OPTIMIZATION.enabled}
              onChange={() =>
                dispatch(
                  actions.setAutomaticOptimizationTabAction({
                    status:
                      status === AUTOMATIC_OPTIMIZATION.enabled
                        ? AUTOMATIC_OPTIMIZATION.disabled
                        : AUTOMATIC_OPTIMIZATION.enabled,
                  }),
                )
              }
            />
          </FormRow>
          {status === AUTOMATIC_OPTIMIZATION.enabled && (
            <FormGroup>
              <FormRow label="Target KPI" tooltip="Select the Key Performance Indicator (KPI) to be used for tiering">
                <Select
                  value={kpi}
                  size="small"
                  onChange={({ target }) => {
                    dispatch(actions.setAutomaticOptimizationTabAction({ kpi: target.value }));
                  }}
                >
                  {(format === DEMAND_TAG_FORMAT.video
                    ? AUTOMATIC_OPTIMIZATION_KPI_VIDEO
                    : AUTOMATIC_OPTIMIZATION_KPI_DISPLAY
                  ).map((item) => (
                    <MenuItem value={item.value} key={item.value}>
                      {item.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>
              <FormRow
                label="Data Look-Back Period"
                tooltip="Specify the time frame for historical data to be considered in the analysis"
              >
                <Select
                  labelId="kpi-select-label"
                  id="kpi-select"
                  value={period}
                  size="small"
                  onChange={({ target }) => {
                    dispatch(actions.setAutomaticOptimizationTabAction({ period: target.value }));
                  }}
                >
                  {AUTOMATIC_OPTIMIZATION_PERIOD.map((item) => (
                    <MenuItem value={item.value} key={item.value}>
                      {item.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>
              <FormRow label="Update Frequency" tooltip="Specify how often the process should run">
                <Select
                  labelId="kpi-select-label"
                  id="kpi-select"
                  value={frequency}
                  variant="outlined"
                  size="small"
                  onChange={({ target }) => {
                    dispatch(actions.setAutomaticOptimizationTabAction({ frequency: target.value }));
                  }}
                >
                  {AUTOMATIC_OPTIMIZATION_FREQUENCY.map((item) => (
                    <MenuItem value={item.value} key={item.value}>
                      {item.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>
              <FormRow label="Maximum Number of HB Tiers">
                <Select
                  value={hbTiers}
                  size="small"
                  onChange={({ target }) => {
                    dispatch(actions.setAutomaticOptimizationTabAction({ hbTiers: target.value }));
                  }}
                >
                  {AUTOMATIC_OPTIMIZATION_TIERS.map((item) => (
                    <MenuItem value={item.value} key={item.value}>
                      {item.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormRow>
              <FormRow
                label="Max In-Tier KPI Gap (%)"
                tooltip="Specify the maximum allowable percentage difference between tags
                  in the same tier for the selected KPI. Note: This rule may not necessarily apply to
                  the last tier, as all remaining tags will be included in it to respect the total
                  number of tiers specified."
              >
                <TextField
                  type="number"
                  size="small"
                  value={kpiGap}
                  placeholder="Enter Max In-Tier KPI Gap"
                  {...getRequiredInputProps({
                    fieldName: 'kpiGap',
                    error: !!errors?.kpiGap?.length,
                  })}
                  onKeyDown={integerFieldBlockInvalidChar}
                  onChange={({ target }) => {
                    const { kpiGap: kpiGapError, ...restErrors } = errors;
                    if (!target.value?.length || (target.value > 0 && target.value < 100)) {
                      dispatch(
                        actions.setAutomaticOptimizationTabAction({
                          kpiGap: target.value?.length ? parseInt(target.value, 10).toString() : target.value,
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>
            </FormGroup>
          )}
        </FormSection>
      </FormContent>
    </Form>
  );
}

export default AutomaticOptimizationTab;
