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

import { CustomTagsPropType } from '../../../../../constants/propTypes';

import { tagsOptionsSelector } from '../../../../../redux/selectors';
import { getCustomTagsOptionsAction } from '../../../../../redux/slices';

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

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

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

  const tagsOptions = useSelector(tagsOptionsSelector);

  const handleGetTagOptions = (searchText = '') => {
    dispatch(
      getCustomTagsOptionsAction({
        searchText,
        category: props.tag.category,
        accountId: props.accountId,
      }),
    );
  };

  const handleChangeTag = (selectedTag) => {
    props.onEdit(selectedTag, props.tag);
    props.onClose();
  };

  return (
    <Popover
      open={props.isOpen}
      anchorEl={props.anchorEl}
      onClose={props.onClose}
      PaperProps={{
        classes: {
          root: styles.PopoverPaper,
        },
      }}
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
      transformOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
    >
      <Paper elevation={5} className={styles.Paper}>
        <Autocomplete
          size="small"
          loading={!tagsOptions}
          options={tagsOptions || []}
          optionValueKey="label"
          filterOptions={(options) => {
            const filteredOptions = options.filter((option) => {
              const isExist = props.tags.some(
                (currentTag) =>
                  currentTag.labelId === props.tag.id &&
                  currentTag.name === props.tag.category &&
                  currentTag.value === option.value,
              );

              return !isExist;
            });

            return filteredOptions;
          }}
          renderInput={(params) => <TextField {...params} size="small" variant="outlined" placeholder="Select tag" />}
          onOpen={() => handleGetTagOptions()}
          onInputChange={(e, searchText) => handleGetTagOptions(searchText)}
          onChange={(e, selectedTag) => handleChangeTag(selectedTag)}
        />
      </Paper>
    </Popover>
  );
}

EditTag.propTypes = {
  // form props
  isOpen: PropTypes.bool.isRequired,
  anchorEl: PropTypes.node.isRequired,
  accountId: PropTypes.number.isRequired,
  tag: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  tags: CustomTagsPropType.isRequired,
  onClose: PropTypes.func.isRequired,
  onEdit: PropTypes.oneOf([null, PropTypes.func]).isRequired,
};

export default EditTag;
