import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { stringify } from 'qs';

import * as selectors from '../../redux/selectors';
import * as actions from '../../redux/slices';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { canSelectAccount } from '@/modules/analytics/general/helpers';

import { Autocomplete, Grid, TextField } from '@/mui/components';

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

function Menu({ isMenuActive = false, ...props }) {
  const dispatch = useDispatch();

  const account = useSelector(selectors.accountSelector);
  const accountOptions = useSelector(selectors.accountOptionsSelector);
  const menu = useSelector(selectors.getMenuSelector);
  const selectedAnalytic = useSelector(selectors.selectedAnalyticSelector);

  const router = useRouter();
  const userPermissions = useSelector(getUserPermissionsSelector);

  const handleAccountChange = (value) => {
    const query = {
      selectedAnalytic,
      publisherName: value.label,
      salesforceId: value.salesforceId,
    };

    dispatch(actions.setFieldAction({ account }));

    router.push(`/analytics?${stringify(query)}`);
  };

  useEffect(() => {
    dispatch(actions.getMenuItemsAction());
    dispatch(
      actions.setFieldAction({
        storedInHouseMenuSettings: props.inHouseMenuSettings,
      }),
    );
  }, []);

  useEffect(() => {
    if (isMenuActive) {
      dispatch(actions.getMenuItemsAction());
    }
  }, [isMenuActive]);

  return (
    <Grid container>
      {canSelectAccount(userPermissions) && (
        <Grid container className={styles.AccountWrapper}>
          <Autocomplete
            id="account"
            disableClearable
            fullWidth
            value={account}
            loading={!accountOptions}
            options={accountOptions || []}
            size="small"
            clear="true"
            onChange={(e, accountValue) => handleAccountChange(accountValue)}
            onOpen={() => {
              dispatch(actions.setFieldAction({ accountOptions: null }));
              dispatch(actions.getAccountOptionsAction(''));
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                size="small"
                data-id="account-input"
                value=""
                placeholder="Account"
                onChange={({ target }) => dispatch(actions.getAccountOptionsAction(target.value))}
              />
            )}
          />
        </Grid>
      )}
      {props.children(menu)}
    </Grid>
  );
}

Menu.propTypes = {
  inHouseMenuSettings: PropTypes.shape({}).isRequired,
  isMenuActive: PropTypes.bool,
  children: PropTypes.func.isRequired,
};

export default Menu;
