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

import { DEMAND_SOURCE_FILTER_NAME, FILTERS_LIST, HUB_FILTER_NAME } from '../../../../constants';

import * as selectors from '../../../../redux/selectors';
import * as actions from '../../../../redux/slices';

import Filter from './components/Filter';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from '@/mui/components';

import styles from './FilterDialog.module.scss';

function FiltersDialog(props) {
  const dispatch = useDispatch();

  const checkedMetrics = useSelector(selectors.checkedMetricsSelector);
  const filters = useSelector(selectors.filtersSelector);

  const getDemandSources = (o) => dispatch(actions.getDemandSourcesAction(o));
  const getHubs = (o) => dispatch(actions.getHubsAction(o));

  const FILTERS_ACTIONS = {
    [DEMAND_SOURCE_FILTER_NAME]: getDemandSources,
    [HUB_FILTER_NAME]: getHubs,
  };

  const getPrevState = () =>
    FILTERS_LIST.reduce(
      (acc, cur) => ({
        ...acc,
        [`${cur.name}_FILTER_VALUES`]: filters[`${cur.name}_FILTER_VALUES`],
        [`${cur.name}_FILTER_ACTION`]: filters[`${cur.name}_FILTER_ACTION`],
      }),
      {},
    );

  const [filtersState, setFiltersState] = useState(getPrevState());

  useEffect(() => {
    dispatch(actions.getDemandSourcesAction());
    dispatch(actions.getHubsAction());
    dispatch(actions.getCountriesAction());
    dispatch(actions.getUserPlayersAction());
    dispatch(actions.getUserDomainsAction());
  }, []);

  useEffect(() => {
    if (props.open) {
      setFiltersState(getPrevState());
    }
  }, [props.open]);

  const handleSubmit = () => {
    dispatch(actions.setFieldAction(filtersState));
    props.onSubmit();
  };

  const handleInputChange = (value, filterName) => {
    if (FILTERS_ACTIONS[filterName]) {
      FILTERS_ACTIONS[filterName](value);
    }
  };

  return (
    <Dialog open={props.open} onClose={props.onClose}>
      <DialogTitle onClose={props.onClose}>Manage Filters</DialogTitle>
      <DialogContent>
        <div className={styles.Filters}>
          {FILTERS_LIST.map((item, index) => (
            <Filter
              key={`${+index}-${item.label}`}
              label={item.label}
              name={item.name}
              multiple={item.multiple}
              options={filters[`${item.name}_FILTER_OPTIONS`]}
              values={filtersState[`${item.name}_FILTER_VALUES`]}
              action={filtersState[`${item.name}_FILTER_ACTION`]}
              onChange={(newValue) => {
                setFiltersState({
                  ...filtersState,
                  [`${item.name}_FILTER_VALUES`]: newValue,
                });
              }}
              onInputChange={handleInputChange}
              onChangeAction={(newValue) => {
                setFiltersState({
                  ...filtersState,
                  [`${item.name}_FILTER_ACTION`]: newValue,
                });
              }}
              disabled={item.exceptMetrics?.some((value) => checkedMetrics?.includes(value))}
            />
          ))}
        </div>
      </DialogContent>

      <DialogActions>
        <Button variant="outlined" size="small" color="primary" onClick={props.onClose}>
          Back
        </Button>
        <Button color="primary" size="small" onClick={handleSubmit}>
          Apply Filters
        </Button>
      </DialogActions>
    </Dialog>
  );
}

FiltersDialog.propTypes = {
  open: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired,
};

export default FiltersDialog;
