import { useEffect, useState } from '@wordpress/element';
import classNames from 'classnames';
import { Button, Popover as WordpressPopover } from '@wordpress/components';
import Cross2Icon from 'blockbite-icons/dist/Cross2';

type PopoverProps = {
  children: React.ReactNode;
  className?: string;
  defaultValue?: string;
  value?: string;
  position?: any;
  visible?: boolean;
  onVisibleChange?: (value: boolean) => void;
};

export const Popover: React.FC<PopoverProps> = ({
  children,
  className,
  position,
  visible,
  onVisibleChange,
}) => {
  const [isVisible, setIsVisible] = useState<boolean>(!!visible);

  useEffect(() => {
    if (visible !== undefined) {
      setIsVisible(visible);
    }
  }, [visible]);

  const toggleVisible = () => {
    const newValue = !isVisible;
    setIsVisible(newValue);
    onVisibleChange && onVisibleChange(newValue);
  };

  return (
    <>
      {isVisible && (
        <WordpressPopover
          position={position}
          className={classNames('blockbite-ui__popover', className)}
          onFocusOutside={() => {
            setIsVisible(false);
            onVisibleChange && onVisibleChange(false);
          }}
        >
          <div className="relative h-full w-full p-4">
            <Button
              onClick={toggleVisible}
              size="small"
              className="close-button absolute right-0 top-0"
            >
              <Cross2Icon />
            </Button>
            {children}
          </div>
        </WordpressPopover>
      )}
    </>
  );
};

export default Popover;
