'use client';

import * as Popover from '@radix-ui/react-popover';
import clsx from 'clsx';
import { EmojiStyle, PickerProps } from 'emoji-picker-react';
import dynamic from 'next/dynamic';
import { memo } from 'react';
import { twMerge } from 'tailwind-merge';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { PlusIcon } from '@/icons';
import { colorVar } from '@/utils/utils';

export type Props = PickerProps & {
  disablePortal?: boolean;
};

// load this dynamically to avoid SSR issues: https://github.com/ealush/emoji-picker-react?tab=readme-ov-file#nextjs
const EmojiPicker = dynamic(
  () => {
    return import('emoji-picker-react');
  },
  { ssr: false }
);

const DEFAULT_REACTIONS = [
  '1f525', // 🔥
  '1f60d', // 😍
  '1f631', // 😱
  '1f64c', // 🙌
  '1f44d', // 👍
  '1f44e', // 👎
  '1f975', // 🥵
];

const EMOJI_PICKER_STYLES = {
  '--epr-highlight-color': colorVar('white'),
  '--epr-hover-bg-color': colorVar('background/glass/thick'),
  '--epr-hover-bg-color-reduced-opacity': 'var(--epr-hover-bg-color)',
  '--epr-focus-bg-color': 'var(--epr-hover-bg-color)',
  '--epr-text-color': colorVar('foreground/primary'),
  '--epr-picker-border-color': colorVar('border/primary'),
  '--epr-bg-color': colorVar('background/secondary'),
  '--epr-reactions-bg-color': 'transparent',
  '--epr-category-icon-active-color': colorVar('foreground/primary'),
  '--epr-horizontal-padding': '0.5rem',
  '--epr-picker-border-radius': '0.5rem',
  /* Header */
  '--epr-header-padding': '0.5rem',
  /* Skin Tone Picker */
  '--epr-skin-tone-picker-menu-color': 'transparent',
  '--epr-skin-tone-outer-border-color': 'transparent',
  '--epr-skin-tone-inner-border-color': 'transparent',
  '--epr-active-skin-tone-indicator-border-color':
    colorVar('background/primary'),
  '--epr-active-skin-hover-color': 'var(--epr-hover-bg-color)',
  /* Search */
  '--epr-search-border-color': 'transparent',
  '--epr-search-input-bg-color': colorVar('background/tertiary'),
  '--epr-search-input-bg-color-active': 'var(--epr-search-input-bg-color)',
  '--epr-search-input-text-color': colorVar('foreground/tertiary'),
  '--epr-search-input-placeholder-color': colorVar('foreground/inactive'),
  '--epr-search-input-padding': '0 0.5rem 0 2rem',
  '--epr-search-input-border-radius': '0.375rem',
  '--epr-search-input-height': '2.5rem',
  '--epr-search-bar-inner-padding': 'var(--epr-horizontal-padding)',
  /*  Category Navigation */
  '--epr-category-navigation-button-size': '1.5rem',
  /* Variation Picker */
  '--epr-emoji-variation-picker-height': '2.5rem',
  '--epr-emoji-variation-picker-bg-color': 'var(--epr-bg-color)',
  /*  Preview */
  '--epr-preview-height': '4rem',
  '--epr-preview-text-size': '0.875rem',
  '--epr-preview-text-padding': '0 var(--epr-horizontal-padding)',
  '--epr-preview-border-color': colorVar('border/primary'),
  '--epr-preview-text-color': colorVar('foreground/tertiary'),
  /* Category */
  '--epr-category-label-bg-color': colorVar('background/secondary', 0.7),
  '--epr-category-label-text-color': colorVar('foreground/secondary'),
  '--epr-category-padding': '0 var(--epr-horizontal-padding)',
  /*  Emoji */
  '--epr-emoji-size': '1.5rem',
  '--epr-emoji-padding': '0.5rem',
  '--epr-emoji-fullsize': '2.5rem',
  '--epr-emoji-hover-color': 'var(--epr-hover-bg-color)',
  '--epr-emoji-variation-indicator-color': 'var(--epr-picker-border-color)',
  '--epr-emoji-variation-indicator-color-hover': 'var(--epr-text-color)',
} as React.CSSProperties;

const CommentEmojiPicker: React.FC<Props> = (props) => {
  const {
    className,
    allowExpandReactions,
    disablePortal = false,
    ...restProps
  } = props;

  const popoverContent = (
    <Popover.Content
      align='start'
      side='top'
      sideOffset={-40}
      className={clsx(
        'z-10 min-w-[160px]',
        'box-shadow',
        'font-sans text-sm font-medium',
        // label
        '[&_.epr-emoji-category-label]:font-sans [&_.epr-emoji-category-label]:text-sm [&_.epr-emoji-category-label]:font-semibold',
        // hide preview
        '[&_.epr-body+div]:hidden',
        '[&_.epr-body]:pb-2'
      )}
    >
      <EmojiPicker
        reactionsDefaultOpen={false}
        allowExpandReactions={false}
        style={{ ...EMOJI_PICKER_STYLES, maxWidth: '80vh' }}
        emojiStyle={EmojiStyle.NATIVE}
        reactions={DEFAULT_REACTIONS}
        autoFocusSearch
        height={300}
        {...restProps}
      />
    </Popover.Content>
  );

  const renderedPopoverContent = disablePortal ? (
    popoverContent
  ) : (
    <Popover.Portal>{popoverContent}</Popover.Portal>
  );

  return (
    <div className={twMerge('relative', className)}>
      <Popover.Root>
        <Popover.Anchor>
          <div className='flex flex-row items-center justify-start'>
            <EmojiPicker
              reactionsDefaultOpen
              allowExpandReactions={false}
              style={{
                ...EMOJI_PICKER_STYLES,
                display: 'block',
                border: 'none',
              }}
              emojiStyle={EmojiStyle.NATIVE}
              width='100%'
              reactions={DEFAULT_REACTIONS}
              {...restProps}
            />
            {allowExpandReactions ? (
              <Popover.Trigger asChild>
                <Button
                  className='cursor-pointer'
                  enableHoverState
                  icon={PlusIcon}
                  active={false}
                  variant={ButtonVariant.Secondary}
                  size={ButtonSize.Mini}
                  shape={ButtonShape.Pill}
                />
              </Popover.Trigger>
            ) : null}
          </div>
        </Popover.Anchor>
        {allowExpandReactions ? renderedPopoverContent : null}
      </Popover.Root>
    </div>
  );
};

export default memo(CommentEmojiPicker);
