import { type Key, useState } from 'react';

import Dropdown from '@design-system/Dropdown';
import List from '@design-system/List';
import ListItem from '@design-system/List/components/ListItem';

import { type DropdownOptionItem } from './types';

type DropdownListProps<TValue> = {
  options: DropdownOptionItem<TValue>[];
  onChange: (item: DropdownOptionItem<TValue>) => void;
  value: DropdownOptionItem<TValue>;
  loading?: boolean;
  disabled?: boolean;
};

const DropdownList = <TValue extends Key>({
  options,
  onChange,
  value,
  loading = false,
  disabled = false,
}: DropdownListProps<TValue>) => {
  const [open, setOpen] = useState(false);
  return (
    <Dropdown
      label={value.name}
      position="left"
      open={open}
      onOpen={() => setOpen(true)}
      onClose={() => setOpen(false)}
      buttonProps={{
        size: 'small',
        disabled,
      }}
    >
      <List sx={{ width: 300, maxHeight: 360 }}>
        {options.map(item => (
          <ListItem
            key={item.id}
            onClick={() => {
              onChange(item);
              setOpen(false);
            }}
            text={{
              title: item.name,
              description: item.description,
            }}
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
              cursor: 'pointer',
              backgroundColor: theme =>
                value.id === item.id
                  ? theme.palette.new.action.background.neutral.hover
                  : 'transparent',
              '&:hover': {
                backgroundColor: theme =>
                  theme.palette.new.action.background.neutral.hover,
              },
            }}
          />
        ))}
        {loading && <ListItem loading />}
      </List>
    </Dropdown>
  );
};

export default DropdownList;
