import React, { useRef, useState } from 'react';
import { SilkeButton, SilkeButtonProps } from './silke-button';
import { SilkePopoverProps } from '../silke-popover';
import { SilkeList } from '../silke-list';
import { SilkePopoverNative } from '../silke-popover-native';
import type { SilkeListItemType } from '../silke-list/types';
import { PopoverPlacement } from '../silke-popover-native/types';

export type SilkeDropdownButtonProps = {
  items?: SilkeListItemType[];
  placement?: PopoverPlacement;
  matchWidth?: boolean;
  animate?: boolean;
  size?: 's' | 'base';
  closeOnSelect?: boolean;
} & SilkeButtonProps &
  Omit<SilkePopoverProps, 'anchor' | 'hide' | 'children' | 'kind'>;

export function SilkeDropdownButton({
  label,
  icon,
  items = [],
  offsetX,
  offsetY = 2,
  placement = 'bottom-end',
  matchWidth = false,
  size = 'base',
  animate = false,
  closeOnSelect = false,
  ...rest
}: SilkeDropdownButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useRef<HTMLButtonElement>(null);

  return (
    <>
      <SilkeButton
        ref={ref}
        label={label}
        icon={icon || (isOpen ? 'chevron.up' : 'chevron.down')}
        aria-expanded={isOpen}
        aria-label="Menu"
        aria-haspopup="true"
        selected={isOpen}
        onClick={() => setIsOpen(!isOpen)}
        {...rest}
      />

      <SilkePopoverNative
        anchor={ref}
        hide={!isOpen}
        offsetX={offsetX}
        offsetY={offsetY}
        placement={placement}
        matchWidth={matchWidth}
        hideBackdrop
        animate={animate}
        onRequestClose={() => setIsOpen(false)}
        shadow="level4"
      >
        <SilkeList
          items={items || []}
          size={size}
          maxHeight={400}
          onSelect={() => closeOnSelect && setIsOpen(false)}
        />
      </SilkePopoverNative>
    </>
  );
}
