import { IconButton, PopoverMenu, TextButton } from '@wix/design-system';
import React, { useImperativeHandle, useRef, forwardRef } from 'react';
import { observer } from 'mobx-react-lite';
import {
  ChevronDown,
  MoreSmall,
  Confirm,
  Duplicate,
  Edit,
  Delete,
  Flag,
  FlagDismiss,
  Pin,
  Revert,
} from '@wix/wix-ui-icons-common';
import { FiltersMap } from '@wix/bex-core';
import { CollectionViewsState } from '../../state';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface ManageViewPopoverHandle {
  focusTrigger: () => void;
}

export interface ManageViewPopoverProps<T, F extends FiltersMap> {
  state: CollectionViewsState<T, F>;
  origin: string;
  /** When true, renders as an inline IconButton inside the dropdown */
  redesign?: boolean;
}

function _ManageViewPopover<T, F extends FiltersMap>(
  props: ManageViewPopoverProps<T, F>,
  ref: React.Ref<ManageViewPopoverHandle>,
) {
  const container = useWixPatternsContainer();
  const { state, redesign } = props;
  const { views, table, emitter, isViewChanged } = state;
  const buttonRef = useRef<HTMLButtonElement>(null);

  useImperativeHandle(ref, () => ({
    focusTrigger: () => buttonRef.current?.focus(),
  }));

  const { translate: t } = container;

  const triggerElement = redesign ? (
    <IconButton
      ref={buttonRef}
      tabIndex={0}
      size="tiny"
      dataHook="manage-view-popover-button"
      onClick={(e) => {
        // Stop propagation so clicking the 3-dots button doesn't select
        // the dropdown option it sits inside of.
        e.stopPropagation();
        // Prevent default so the click doesn't trigger form submission
        // or other native behavior while inside DropdownLayout.
        e.preventDefault();
      }}
    >
      <MoreSmall />
    </IconButton>
  ) : (
    <TextButton
      size="small"
      as="button"
      dataHook="manage-view-popover-button"
      suffixIcon={<ChevronDown />}
    >
      {t('cairo.manageView.CTA')}
    </TextButton>
  );

  return (
    <PopoverMenu
      minWidth={271}
      {...(redesign && { placement: 'right', appendTo: 'window' })}
      onShow={() => {
        emitter.emit('openManageViewPopoverMenu');
      }}
      dataHook="manage-view-popover"
      triggerElement={triggerElement}
    >
      <PopoverMenu.MenuItem
        text={t('cairo.manageView.saveChanges.CTA')}
        dataHook="save-changes-to-view"
        disabled={
          !views.isCurrentViewSelected ||
          !isViewChanged ||
          views.currentView?.isPreset
        }
        prefixIcon={<Confirm />}
        onClick={() => {
          state.saveViewChanges();
        }}
      />
      {!redesign && (
        <PopoverMenu.MenuItem
          dataHook="save-new-view"
          disabled={views.reachedViewsLimit}
          onClick={() => {
            views.saveViewModal.open();
            table.closeSidePanel();
          }}
          text={t('cairo.manageView.saveNewView.CTA')}
          prefixIcon={<Duplicate />}
        />
      )}
      <PopoverMenu.MenuItem
        dataHook="rename-view"
        disabled={views.currentView?.isPreset || isViewChanged}
        onClick={() => {
          views.renameViewModal.open();
          table.closeSidePanel();
        }}
        text={t('cairo.manageView.Rename.CTA')}
        prefixIcon={<Edit />}
      />
      <PopoverMenu.MenuItem
        dataHook="set-as-default-view"
        disabled={!views.currentView || (isViewChanged && !views.isDefaultView)}
        onClick={() => {
          state.setAsDefaultView();
        }}
        text={
          views.isDefaultView
            ? t('cairo.manageView.setAsDefault.reset.CTA')
            : t('cairo.manageView.setAsDefault.CTA')
        }
        prefixIcon={
          views.isDefaultView ? (
            redesign ? (
              <Revert />
            ) : (
              <FlagDismiss />
            )
          ) : redesign ? (
            <Pin />
          ) : (
            <Flag />
          )
        }
      />
      <PopoverMenu.MenuItem
        dataHook="delete-view"
        disabled={!views.isCurrentViewSelected || views.currentView?.isPreset}
        onClick={() => {
          state.deleteView();
        }}
        text={t('cairo.manageView.Delete.CTA')}
        prefixIcon={<Delete />}
      />
    </PopoverMenu>
  );
}

export const ManageViewPopover = observer(
  forwardRef(_ManageViewPopover),
) as <T, F extends FiltersMap>(
  props: ManageViewPopoverProps<T, F> & {
    ref?: React.Ref<ManageViewPopoverHandle>;
  },
) => React.ReactElement | null;
