import { Box, Text, TextButton, PopoverMenu } from '@wix/design-system';
import { ChevronDown } from '@wix/wix-ui-icons-common';
import { ImportState, WritePolicy } from '@wix/bex-core';
import React from 'react';
import { observer } from 'mobx-react-lite';

// Width of the policy popover. The default WDS `maxWidth` (204) is too narrow
// for "Update the existing items" at the medium menu font, so the label wraps
// to two lines; this matches the field-column width so each option fits on one
// line (per the Figma).
const MENU_MAX_WIDTH = 250;

/**
 * Shown under the row whose CSV column is mapped to the collection `_id` field.
 * Lets the user pick how rows that collide on an existing `_id` are written:
 * update the existing item (`OVERWRITE`) or skip it, keeping the existing data
 * intact (`SKIP_EXISTING`). The inline action label reflects the current choice
 * and opens a popover to switch.
 */
export const IdCollisionControl = observer(function _IdCollisionControl({
  state,
}: {
  state: ImportState;
}) {
  const { translate: t, writePolicy } = state;
  const isSkip = writePolicy === WritePolicy.SKIP_EXISTING;
  const actionLabel = isSkip
    ? t('cairo.import.skipImportedItems')
    : t('cairo.import.updateExistingItems');

  return (
    <Box direction="vertical" gap="0">
      <Text size="tiny" secondary dataHook="import-id-collision-label">
        {t('cairo.import.idCollisionLabel')}
      </Text>
      <PopoverMenu
        appendTo="window"
        zIndex={5001}
        maxWidth={MENU_MAX_WIDTH}
        textSize="small"
        placement="bottom-start"
        dataHook="import-id-collision-menu"
        triggerElement={
          <TextButton
            size="tiny"
            as="button"
            dataHook="import-id-collision-action"
            suffixIcon={<ChevronDown />}
          >
            {actionLabel}
          </TextButton>
        }
      >
        <PopoverMenu.MenuItem
          dataHook="import-id-collision-update"
          text={t('cairo.import.updateExistingItems')}
          onClick={() => state.setWritePolicy(WritePolicy.OVERWRITE)}
        />
        <PopoverMenu.MenuItem
          dataHook="import-id-collision-skip"
          text={t('cairo.import.skipImportedItems')}
          onClick={() => state.setWritePolicy(WritePolicy.SKIP_EXISTING)}
        />
      </PopoverMenu>
    </Box>
  );
});
