import { UploadOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Access } from '@umijs/max';
import { Typography } from 'antd';
import React from 'react';
import type { ProductFormValues, ProductItem } from '../data';

const { Text } = Typography;

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

type ProductFormModalProps = {
  intl: IntlLike;
  open: boolean;
  editingId?: string;
  currentRow?: ProductItem;
  categoryOptions: { label: string; value: string }[];
  statusEnum: Record<string, { text: string; status: string }>;
  canViewCostPrice: boolean;
  submitting: boolean;
  formRef: React.MutableRefObject<
    ProFormInstance<ProductFormValues> | undefined
  >;
  onOpenChange: (open: boolean) => void;
  onFinish: (values: ProductFormValues) => Promise<boolean>;
};

const ProductFormModal: React.FC<ProductFormModalProps> = ({
  intl,
  open,
  editingId,
  currentRow,
  categoryOptions,
  statusEnum,
  canViewCostPrice,
  submitting,
  formRef,
  onOpenChange,
  onFinish,
}) => {
  const isOnlineEditing = currentRow?.status === 'online';
  const formInitialValues = React.useMemo(
    () => currentRow || { status: 'draft' },
    [editingId, currentRow],
  );

  return (
    <ModalForm<ProductFormValues>
      formRef={formRef}
      title={
        editingId
          ? intl.formatMessage({
              id: 'pages.product.edit',
              defaultMessage: '编辑商品',
            })
          : intl.formatMessage({
              id: 'pages.product.add',
              defaultMessage: '新增商品',
            })
      }
      open={open}
      onOpenChange={onOpenChange}
      initialValues={formInitialValues}
      layout="vertical"
      width={520}
      modalProps={{
        destroyOnHidden: true,
        maskClosable: false,
      }}
      submitter={{
        submitButtonProps: {
          loading: submitting,
          disabled: submitting,
          icon: <UploadOutlined />,
        },
        resetButtonProps: {
          disabled: submitting,
        },
      }}
      onFinish={onFinish}
    >
      {isOnlineEditing ? (
        <Text type="warning">
          {intl.formatMessage({
            id: 'pages.product.edit.coreDenied',
            defaultMessage: '已上架商品修改核心字段前需先下架',
          })}
        </Text>
      ) : null}
      <ProFormText
        name="name"
        label={intl.formatMessage({
          id: 'product.form.name',
          defaultMessage: '商品名称',
        })}
        disabled={isOnlineEditing}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.name.required',
              defaultMessage: '请输入商品名称',
            }),
          },
        ]}
      />
      <ProFormSelect
        name="category"
        label={intl.formatMessage({
          id: 'product.form.category',
          defaultMessage: '分类',
        })}
        options={categoryOptions}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.category.required',
              defaultMessage: '请选择分类',
            }),
          },
        ]}
      />
      <ProFormText
        name="sku"
        label={intl.formatMessage({
          id: 'product.form.sku',
          defaultMessage: 'SKU',
        })}
        disabled={isOnlineEditing}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.sku.required',
              defaultMessage: '请输入 SKU',
            }),
          },
        ]}
      />
      <ProFormDigit
        name="originalPrice"
        label={intl.formatMessage({
          id: 'product.form.originalPrice',
          defaultMessage: '原价',
        })}
        disabled={isOnlineEditing}
        min={0}
        fieldProps={{ precision: 2, prefix: '￥' }}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.originalPrice.required',
              defaultMessage: '请输入原价',
            }),
          },
          {
            validator: async (_rule: unknown, value: number | undefined) => {
              if (!value || value <= 0) {
                throw new Error(
                  intl.formatMessage({
                    id: 'product.form.originalPrice.invalid',
                    defaultMessage: '原价必须大于 0',
                  }),
                );
              }
            },
          },
        ]}
      />
      <ProFormDigit
        name="salePrice"
        label={intl.formatMessage({
          id: 'product.form.salePrice',
          defaultMessage: '售价',
        })}
        disabled={isOnlineEditing}
        min={0}
        fieldProps={{ precision: 2, prefix: '￥' }}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.salePrice.required',
              defaultMessage: '请输入售价',
            }),
          },
          {
            validator: async (_rule: unknown, value: number | undefined) => {
              const original = formRef.current?.getFieldValue(
                'originalPrice',
              ) as number | undefined;
              if (!value || value <= 0 || (original && value > original)) {
                throw new Error(
                  intl.formatMessage({
                    id: 'product.form.salePrice.invalid',
                    defaultMessage: '售价必须大于 0 且不高于原价',
                  }),
                );
              }
            },
          },
        ]}
      />
      <Access accessible={canViewCostPrice} fallback={null}>
        <ProFormDigit
          name="costPrice"
          label={intl.formatMessage({
            id: 'product.form.costPrice',
            defaultMessage: '成本价',
          })}
          min={0}
          fieldProps={{ precision: 2, prefix: '￥' }}
        />
      </Access>
      <ProFormDigit
        name="stock"
        label={intl.formatMessage({
          id: 'product.form.stock',
          defaultMessage: '库存',
        })}
        min={0}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.stock.required',
              defaultMessage: '请输入库存',
            }),
          },
        ]}
      />
      <ProFormDigit
        name="safetyStock"
        label={intl.formatMessage({
          id: 'product.form.safetyStock',
          defaultMessage: '安全库存',
        })}
        min={0}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.safetyStock.required',
              defaultMessage: '请输入安全库存',
            }),
          },
        ]}
      />
      <ProFormSelect
        name="status"
        label={intl.formatMessage({
          id: 'product.form.status',
          defaultMessage: '状态',
        })}
        valueEnum={statusEnum}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'product.form.status.required',
              defaultMessage: '请选择状态',
            }),
          },
        ]}
      />
      <ProFormTextArea
        name="description"
        label={intl.formatMessage({
          id: 'product.form.description',
          defaultMessage: '商品描述',
        })}
        fieldProps={{ maxLength: 300, showCount: true }}
      />
      <ProFormText
        name="imageUrl"
        label={intl.formatMessage({
          id: 'product.form.imageUrl',
          defaultMessage: '图片地址',
        })}
      />
    </ModalForm>
  );
};

export default ProductFormModal;
