import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import { autocompleteClasses } from '@mui/material';
import { useTheme } from '@mui/material/styles';

import { TagSelector } from '@/modules/@common/TagSelector';
import { List, ListItem, ListSubheader, Stack, Typography } from '@/mui/components';

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

function ActionAutocomplete({
  onInputChange = () => {},
  onOpen = null,
  onChange = null,
  value = [],
  groupBy = null,
  disabled = false,
  size = 'medium',
  placeholder = null,
  ...props
}) {
  const theme = useTheme();
  const [list, setList] = useState(value || []);
  const [include, setInclude] = useState(!list.length || list.some((o) => o.include));

  useEffect(() => {
    const list$ = value || [];

    setInclude(!list$.length || list$.some((o) => o.include));
    setList(list$);
  }, [value]);

  const renderGroup = (params) => {
    const [name, , color] = (params.group || '').split('|');

    const optionList = (
      <List
        disablePadding
        className={classNames(autocompleteClasses.groupUl, styles.Group, {
          [styles.Group___indent]: params.group,
        })}
      >
        {params.children}
      </List>
    );

    return params.group ? (
      <ListItem key={`${params.key}-${name}-${color}`} disablePadding>
        <Stack fullWidth>
          <ListSubheader
            className={classNames(autocompleteClasses.groupLabel, styles.GroupLabel)}
            style={{
              color: color ? theme.palette.getContrastText(color) : null,
              backgroundColor: color ?? null,
            }}
            component="div"
          >
            <Typography variant="subtitle1" component="div">
              {name}
            </Typography>
          </ListSubheader>
          {optionList}
        </Stack>
      </ListItem>
    ) : (
      optionList
    );
  };

  return (
    <TagSelector
      {...props}
      groupBy={groupBy}
      disabled={disabled}
      selectProps={{
        disabled: !!list.length,
      }}
      include={include}
      renderGroup={renderGroup}
      size={size}
      value={list}
      options={props.options?.filter((option) => !list.some((item) => item.value === option.value)) ?? []}
      placeholder={placeholder}
      onOpen={() => {
        if (onOpen) {
          onOpen('');
        }
      }}
      onChange={(e, tags) => {
        onChange(tags);
        setList(tags);
      }}
      onInputChange={(e) => {
        if (onInputChange) {
          onInputChange(e.target.value);
        }
      }}
    />
  );
}

ActionAutocomplete.propTypes = {
  id: PropTypes.string.isRequired,
  options: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  onInputChange: PropTypes.func,
  onChange: PropTypes.func,
  onOpen: PropTypes.func,
  value: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string,
      value: PropTypes.string,
    }),
  ),
  groupBy: PropTypes.func,
  disabled: PropTypes.bool,
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']),
  placeholder: PropTypes.string,
};

export default ActionAutocomplete;
