// Copyright 2025 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import type { ReactNode } from 'react';
import React, { memo, useCallback, useState } from 'react';
import type { Placement } from 'react-aria';
import { DialogTrigger } from 'react-aria-components';
import { FunPopover } from './base/FunPopover';
import type { FunEmojiSelection } from './panels/FunPanelEmojis';
import { FunPanelEmojis } from './panels/FunPanelEmojis';

export type FunEmojiPickerProps = Readonly<{
  placement?: Placement;
  defaultOpen?: boolean;
  onOpenChange?: (isOpen: boolean) => void;
  onSelectEmoji: (emojiSelection: FunEmojiSelection) => void;
  children: ReactNode;
}>;

export const FunEmojiPicker = memo(function FunEmojiPicker(
  props: FunEmojiPickerProps
): JSX.Element {
  const { onOpenChange } = props;
  const [isOpen, setIsOpen] = useState(props.defaultOpen ?? false);

  const handleOpenChange = useCallback(
    (nextIsOpen: boolean) => {
      setIsOpen(nextIsOpen);
      onOpenChange?.(nextIsOpen);
    },
    [onOpenChange]
  );

  const handleClose = useCallback(() => {
    setIsOpen(false);
  }, []);

  return (
    <DialogTrigger isOpen={isOpen} onOpenChange={handleOpenChange}>
      {props.children}
      <FunPopover placement={props.placement}>
        <FunPanelEmojis
          onEmojiSelect={props.onSelectEmoji}
          onClose={handleClose}
        />
      </FunPopover>
    </DialogTrigger>
  );
});
