import { productcontrollerCreateproduct } from '@/servers/api/product';
import { templatecontrollerRendertemplate } from '@/servers/api/template';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { App, Descriptions, Form, Tag } from 'antd';
import React, { useEffect } from 'react';

interface CreateModalProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  category: { id: number; name: string } | null;
  permutation: Record<string, any>;
  attributes: any[]; // The attribute definitions
}

const capitalize = (s: string) => s.charAt(0).toLocaleUpperCase() + s.slice(1);

const CreateModal: React.FC<CreateModalProps> = ({
  visible,
  onClose,
  onSuccess,
  category,
  permutation,
  attributes,
}) => {
  const { message } = App.useApp();
  const [form] = Form.useForm();

  // Helper to generate default name based on attributes
  const generateDefaultName = () => {
    if (!category) return '';
    const parts = [category.name];
    attributes.forEach((attr) => {
      const val = permutation[attr.name];
      if (val) parts.push(val.name);
    });
    return parts.join(' - ');
  };

  useEffect(() => {
    if (visible && permutation) {
      const generateSku = async () => {
        try {
          // Extract values from permutation based on known keys
          // Keys in permutation are dict names (e.g. 'brand', 'strength')
          const brand = permutation['brand']?.name || '';
          const strength = permutation['strength']?.name || '';
          const flavor = permutation['flavor']?.name || '';
          const humidity = permutation['humidity']?.name || '';
          const model = permutation['model']?.name || '';

          const variables = {
            brand,
            strength,
            flavor,
            model,
            humidity: humidity ? capitalize(humidity) : '',
          };

          const { success, data: rendered } =
            await templatecontrollerRendertemplate(
              { name: 'product.sku' },
              variables,
            );

          if (success && rendered) {
            form.setFieldValue('sku', rendered);
          }
        } catch (error) {
          console.error('Failed to generate SKU', error);
        }
      };

      generateSku();
      form.setFieldValue('name', generateDefaultName());
    }
  }, [visible, permutation, category]);

  return (
    <ModalForm
      title="创建产品"
      open={visible}
      form={form}
      modalProps={{
        onCancel: onClose,
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        if (!category) return false;

        // Construct attributes payload
        // Expected format: [{ dictName: 'Size', name: 'S' }, ...]
        const payloadAttributes = attributes
          .filter((attr) => permutation[attr.name])
          .map((attr) => ({
            dictName: attr.name,
            name: permutation[attr.name].name,
          }));

        const payload = {
          name: values.name,
          sku: values.sku,
          categoryId: category.id,
          attributes: payloadAttributes,
          type: 'single', // Default to single
        };

        try {
          const { success, message: errMsg } =
            await productcontrollerCreateproduct(payload as any);
          if (success) {
            message.success('产品创建成功');
            onSuccess();
            return true;
          } else {
            message.error(errMsg || '创建产品失败');
            return false;
          }
        } catch (error) {
          message.error('发生错误');
          return false;
        }
      }}
    >
      <Descriptions
        column={1}
        bordered
        size="small"
        style={{ marginBottom: 24 }}
      >
        <Descriptions.Item label="分类">{category?.name}</Descriptions.Item>
        <Descriptions.Item label="属性">
          {attributes.map((attr) => {
            const val = permutation[attr.name];
            if (!val) return null;
            return (
              <Tag key={attr.name}>
                {attr.title || attr.name}: {val.name}
              </Tag>
            );
          })}
        </Descriptions.Item>
      </Descriptions>

      <ProFormText
        name="sku"
        label="SKU"
        placeholder="请输入 SKU"
        rules={[{ required: true, message: '请输入 SKU' }]}
      />

      <ProFormText
        name="name"
        label="产品名称"
        placeholder="请输入产品名称"
        rules={[{ required: true, message: '请输入产品名称' }]}
      />
    </ModalForm>
  );
};

export default CreateModal;
