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

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

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 PrimaryTemplate: 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);
    setListItems(
      listItems.map(item => ({
        ...item,
        selected: item.name === selected
      }))
    );
  };

  return (
    <>
      <Select
        {...args}
        className={classes.labelRoot}
        value={selectValue}
        menuContentProps={{
          ...args.menuContentProps,
          handleClick: handleSelectChange,
          listItems
        }}
      />
      {args.error && <FormHelperText style={{ color: 'red' }}>Error</FormHelperText>}
    </>
  );
};
