import { useEffect } from '@wordpress/element';
import { useState } from '@wordpress/element';
import classNames from 'classnames';
import { DropdownMenu } from '@wordpress/components';
import ChevronDownIcon from 'blockbite-icons/dist/ChevronDown';
import { Icon } from '@components/ui/Icon';

type DropdownPickerProps = {
  label?: string;
  className?: string;
  defaultValue: string;
  defaultIcon?: any;
  options: {
    icon?: React.ReactElement;
    label: string;
    subtitle?: string;
    value: string;
  }[];
  onPressedChange: (value: string) => void;
};

export const DropdownPicker = ({
  label,
  className,
  defaultValue,
  defaultIcon = ChevronDownIcon,
  onPressedChange,
  options,
}: DropdownPickerProps) => {
  const [currentOption, setCurrentOption] = useState<string | null>(null);

  useEffect(() => {
    setCurrentOption(defaultValue);
  }, [defaultValue]);

  return (
    <DropdownMenu
      controls={options.map((option) => ({
        icon: option.icon, //
        title: option.label,
        onClick: () => {
          setCurrentOption(option.value);
          onPressedChange(option.value);
        },
      }))}
      className={classNames(
        'blockbite-ui__dropdown-picker border-primary border',
        className
      )}
      icon={
        options.find((option) => option.value === currentOption)?.icon || (
          <Icon icon={defaultIcon} />
        )
      }
      label={label || 'Select'}
    />
  );
};
