import type { SelectProps } from 'antd';
import type { ProductFormValues, ProductItem } from './data';

type IntlLike = {
  formatMessage: (descriptor: { id: string; defaultMessage: string }) => string;
};

export const PRODUCT_CORE_FIELDS = [
  'name',
  'sku',
  'originalPrice',
  'salePrice',
] as const;

type ProductCoreField = (typeof PRODUCT_CORE_FIELDS)[number];

const normalizeCoreFieldValue = (
  field: ProductCoreField,
  value: ProductFormValues[ProductCoreField] | ProductItem[ProductCoreField],
) => {
  if (field === 'originalPrice' || field === 'salePrice') {
    return Number(value);
  }
  return String(value ?? '').trim();
};

export const hasCoreFieldChanged = (
  current: ProductItem,
  values: ProductFormValues,
): boolean => {
  return PRODUCT_CORE_FIELDS.some(
    (field) =>
      normalizeCoreFieldValue(field, values[field]) !==
      normalizeCoreFieldValue(field, current[field]),
  );
};

export const formatPrice = (value: number) => value.toFixed(2);

export const getStatusValueEnum = (intl: IntlLike) => ({
  draft: {
    text: intl.formatMessage({
      id: 'product.status.draft',
      defaultMessage: '草稿',
    }),
    status: 'Default' as const,
  },
  pending_review: {
    text: intl.formatMessage({
      id: 'product.status.pending_review',
      defaultMessage: '待审核',
    }),
    status: 'Warning' as const,
  },
  online: {
    text: intl.formatMessage({
      id: 'product.status.online',
      defaultMessage: '已上架',
    }),
    status: 'Success' as const,
  },
  offline: {
    text: intl.formatMessage({
      id: 'product.status.offline',
      defaultMessage: '已下架',
    }),
    status: 'Default' as const,
  },
  rejected: {
    text: intl.formatMessage({
      id: 'product.status.rejected',
      defaultMessage: '已驳回',
    }),
    status: 'Error' as const,
  },
});

export const getCategoryOptions = (intl: IntlLike): SelectProps['options'] => [
  {
    label: intl.formatMessage({
      id: 'pages.product.category.audio',
      defaultMessage: '音频',
    }),
    value: 'audio',
  },
  {
    label: intl.formatMessage({
      id: 'pages.product.category.peripheral',
      defaultMessage: '外设',
    }),
    value: 'peripheral',
  },
  {
    label: intl.formatMessage({
      id: 'pages.product.category.digital',
      defaultMessage: '数码',
    }),
    value: 'digital',
  },
  {
    label: intl.formatMessage({
      id: 'pages.product.category.wearable',
      defaultMessage: '穿戴',
    }),
    value: 'wearable',
  },
  {
    label: intl.formatMessage({
      id: 'pages.product.category.home',
      defaultMessage: '家电',
    }),
    value: 'home',
  },
];
