/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useState } from 'react';
import cn from 'classnames';
import uniqueId from 'lodash/uniqueId';

import { Menu } from '../Menu';
import { Chip } from './component';
import { useTheme } from '../Theme';
import { ChipMenuProps } from './types.d';

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const ChipMenu = <T extends object>(props: ChipMenuProps<T>) => {
  const { label, items, chipProps, onSelect = () => {}, dataSettings } = props;
  const [isOpen, setIsOpen] = useState(false);

  const theme = useTheme();

  const anchorIconClassNames = cn({
    'dropdown-icon': true,
    open: isOpen,
  });

  const renderAnchor = () => {
    return (
      <Chip
        color="gray"
        label={label}
        variant="default"
        {...chipProps}
        active={isOpen}
        onDelete={() => setIsOpen((prevState) => !prevState)}
        deleteIcon={
          <div className={anchorIconClassNames} style={{ marginRight: '10px' }}>
            <svg width="5" height="8" viewBox="0 0 5 8" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M3.05719 4L0.195262 1.13807C-0.0650874 0.877721 -0.0650874 0.455612 0.195262 0.195262C0.455612 -0.0650873 0.877722 -0.0650873 1.13807 0.195262L4.4714 3.5286C4.73175 3.78895 4.73175 4.21105 4.4714 4.4714L1.13807 7.80474C0.877722 8.06509 0.455612 8.06509 0.195262 7.80474C-0.0650874 7.54439 -0.0650874 7.12228 0.195262 6.86193L3.05719 4Z"
                fill={theme.text.hint}
              />
            </svg>
          </div>
        }
      />
    );
  };
  return (
    <Menu
      PaperProps={{ style: { maxHeight: 28 * 10 } }}
      isOpen={isOpen}
      setIsOpen={setIsOpen}
      className="sq-chip-menu"
      anchor={renderAnchor()}
    >
      {items.map((item) => {
        const title = ((): React.ReactNode => {
          if (dataSettings) {
            return item[dataSettings.titleDesignation] as unknown as React.ReactNode;
          }
          return item['title' as keyof typeof item] as unknown as React.ReactNode;
        })();

        const value = ((): string | number | undefined => {
          if (dataSettings) {
            return item[dataSettings.valueDesignation] as unknown as string | number;
          }
          return item['value' as keyof typeof item] as unknown as string | number | undefined;
        })();

        const key = value?.toString() ?? uniqueId();

        return <Menu.Item key={key} {...item} title={title} onClick={() => onSelect(value)} />;
      })}
    </Menu>
  );
};
