import { useState } from 'react';
import { Story } from '@storybook/react';

import makeStyles from '@mui/styles/makeStyles';

import { DropDownMenuProps } from '../../../../dropdown-menu';
import type { Theme } from '../../../../@styles/theme-provider';

import { Select } from '../../../../@forms/select';
import type { SelectProps } from '../../../../@forms/select';

const createClasses = makeStyles<Theme>(() => ({
  labelRoot: {
    width: '160px'
  }
}));

export const IconAndSearchTemplate: Story<SelectProps> = args => {
  const classes = createClasses();
  const [selectValue, setSelectValue] = useState('');
  const [listItems, setListItems] = useState(args.menuContentProps.listItems);

  const handleSelectChange: NonNullable<DropDownMenuProps['handleClick']> = name => () => {
    const selected = selectValue === name ? '' : name.toString();
    setSelectValue(selected);
    const newItems = listItems.map(item => ({
      ...item,
      selected: item.name === selected
    }));
    setListItems(newItems);
  };

  return (
    <Select
      {...args}
      className={classes.labelRoot}
      value={selectValue}
      menuContentProps={{
        ...args.menuContentProps,
        handleClick: handleSelectChange,
        listItems: listItems,
        defaultListItems: listItems
      }}
    />
  );
};
