/**
 * 产品模态框组件
 * 作者: 阿瑞
 * 功能: 提供产品信息的添加和编辑界面
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'next/navigation';
import { Product } from '@/models/team/types/old/product';
import UploadImage from '@/components/UploadImage';
import { Input, InputNumber, Select, Button, Tag, Form, Card, Row, Col, Alert, Space, Modal, Switch } from 'antd';
import type { InputRef } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import TextArea from 'antd/es/input/TextArea';

// 定义不同的成本数据结构接口
interface ProductCostData {
  costPrice?: number;
  packagingFee?: number;
  shippingFee?: number;
}

interface LegacyCostData {
  base?: number;
  packaging?: number;
  shipping?: number;
}

interface ProductModalProps {
  isOpen: boolean;
  onClose: () => void;
  product?: Product | null;
  onSuccess: () => void;
  suppliers: { id: number; name: string }[];
  brands: { id: number; name: string }[];
  categories: { id: number; name: string }[];
  availableLevels: string[];
}

/**
 * 产品模态框组件
 */
export default function ProductModal({ 
  isOpen, 
  onClose, 
  product, 
  onSuccess,
  suppliers,
  brands,
  categories}: ProductModalProps) {
  const params = useParams();
  const teamCode = params?.teamCode as string;
  const isEditing = !!product;
  const [form] = Form.useForm();
  
  // 表单状态
  const [formData, setFormData] = useState<Partial<Product>>({
    name: '',
    supplierId: undefined,
    brandId: undefined,
    categoryId: undefined,
    description: '',
    code: '',
    image: '',
    sku: '',
    aliases: [],
    level: '',
    cost: { costPrice: 0, packagingFee: 0, shippingFee: 0 },
    price: 0,
    stock: 0
  });
  
  // 品牌和品类选择状态
  const [selectedBrandName, setSelectedBrandName] = useState<string>('');
  const [selectedCategoryName, setSelectedCategoryName] = useState<string>('');
  const [customNamePart, setCustomNamePart] = useState<string>('');
  const [isAutoNameEnabled, setIsAutoNameEnabled] = useState<boolean>(true);
  const [isUpdatingFormName, setIsUpdatingFormName] = useState<boolean>(false);
  
  // Tag编辑相关状态
  const [aliasInput, setAliasInput] = useState('');
  const [inputVisible, setInputVisible] = useState(false);
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);
  const editInputRef = useRef<InputRef>(null);
  
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  /**
   * 处理模态框可见性变化
   */
  useEffect(() => {
    if (isOpen) {
      if (product) {
        // 确保cost字段使用正确的结构
        let normalizedCost: ProductCostData = { costPrice: 0, packagingFee: 0, shippingFee: 0 };
        
        if (product.cost) {
          // 处理可能存在的不同cost字段结构
          if ('costPrice' in product.cost) {
            normalizedCost = {
              costPrice: product.cost.costPrice,
              packagingFee: product.cost.packagingFee,
              shippingFee: product.cost.shippingFee
            };
          } else if ((product.cost as LegacyCostData).base !== undefined) {
            normalizedCost = {
              costPrice: (product.cost as LegacyCostData).base,
              packagingFee: (product.cost as LegacyCostData).packaging,
              shippingFee: (product.cost as LegacyCostData).shipping
            };
          }
        }
        
        const newFormData = {
          id: product.id,
          name: product.name,
          supplierId: product.supplierId,
          brandId: product.brandId,
          categoryId: product.categoryId,
          description: product.description || '',
          code: product.code || '',
          image: product.image || '',
          sku: product.sku || '',
          aliases: product.aliases || [],
          level: product.level || '',
          cost: normalizedCost,
          price: product.price,
          stock: product.stock
        };
        
        setFormData(newFormData);
        form.setFieldsValue(newFormData);
        
        // 在编辑模式下，获取品牌和品类名称
        if (product.brandId) {
          const brand = brands.find(b => b.id === product.brandId);
          if (brand) {
            setSelectedBrandName(brand.name);
          }
        }
        
        if (product.categoryId) {
          const category = categories.find(c => c.id === product.categoryId);
          if (category) {
            setSelectedCategoryName(category.name);
          }
        }
        
        // 编辑模式下默认禁用自动命名，避免覆盖已有名称
        setIsAutoNameEnabled(false);
        
        // 从产品名称中提取自定义部分
        const prefix = `${selectedBrandName}${selectedCategoryName}`;
        if (prefix && product.name.startsWith(prefix)) {
          setCustomNamePart(product.name.substring(prefix.length));
        } else {
          setCustomNamePart(product.name);
        }
      } else {
        // 重置表单
        const initialData = {
          name: '',
          supplierId: undefined,
          brandId: undefined,
          categoryId: undefined,
          description: '',
          code: '',
          image: '',
          sku: '',
          aliases: [],
          level: '',
          cost: { costPrice: 0, packagingFee: 0, shippingFee: 0 },
          price: 0,
          stock: 0
        };
        
        setFormData(initialData);
        form.resetFields();
        form.setFieldsValue(initialData);
        
        // 新建模式下重置相关状态
        setSelectedBrandName('');
        setSelectedCategoryName('');
        setCustomNamePart('');
        setIsAutoNameEnabled(true);
      }
      
      setAliasInput('');
      setInputVisible(false);
      setEditInputIndex(-1);
      setEditInputValue('');
      setError(null);
    }
  }, [product, isOpen, form, brands, categories]);
  
  // 聚焦输入框
  useEffect(() => {
    if (inputVisible && isOpen) {
      inputRef.current?.focus();
    }
  }, [inputVisible, isOpen]);
  
  // 聚焦编辑输入框
  useEffect(() => {
    if (editInputIndex >= 0 && isOpen) {
      editInputRef.current?.focus();
    }
  }, [editInputIndex, isOpen]);
  
  /**
   * 显示输入框
   */
  const showInput = () => {
    setInputVisible(true);
  };

  /**
   * 处理输入框值变化
   */
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAliasInput(e.target.value);
  };

  /**
   * 处理输入确认
   */
  const handleInputConfirm = () => {
    if (!isOpen) return;
    
    if (aliasInput && aliasInput.trim() && !formData.aliases?.includes(aliasInput.trim())) {
      const newAliases = [...(formData.aliases || []), aliasInput.trim()];
      setFormData(prev => ({
        ...prev,
        aliases: newAliases
      }));
      form.setFieldValue('aliases', newAliases);
    }
    setInputVisible(false);
    setAliasInput('');
  };

  /**
   * 处理Tag编辑状态
   */
  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value);
  };

  /**
   * 开始编辑别名
   */
  const startEdit = (index: number) => {
    setEditInputIndex(index);
    setEditInputValue(formData.aliases?.[index] || '');
  };

  /**
   * 处理编辑确认
   */
  const handleEditInputConfirm = () => {
    if (!isOpen) return;
    
    const newAliases = [...(formData.aliases || [])];
    if (editInputValue && editInputValue.trim() && !newAliases.includes(editInputValue.trim()) && editInputIndex >= 0) {
      newAliases[editInputIndex] = editInputValue.trim();
      setFormData(prev => ({
        ...prev,
        aliases: newAliases
      }));
      form.setFieldValue('aliases', newAliases);
    }
    setEditInputIndex(-1);
    setEditInputValue('');
  };

  /**
   * 删除产品别名
   */
  const handleRemoveAlias = (index: number) => {
    if (!isOpen) return;
    
    const newAliases = formData.aliases?.filter((_, i) => i !== index) || [];
    setFormData(prev => ({
      ...prev,
      aliases: newAliases
    }));
    form.setFieldValue('aliases', newAliases);
  };
  
  /**
   * 处理图片上传成功
   */
  const handleImageUploadSuccess = (imageUrl: string) => {
    if (!isOpen) return;
    
    // 获取旧图片URL
    const oldImageUrl = formData.image;
    
    // 更新表单数据和表单字段
    setFormData(prev => ({
      ...prev,
      image: imageUrl
    }));
    form.setFieldValue('image', imageUrl);
    
    // 如果是更新图片（且旧图片以/api/tools/images/开头），则尝试删除旧图片
    if (oldImageUrl && oldImageUrl.startsWith('/api/tools/images/')) {
      try {
        // 发送删除请求
        fetch(oldImageUrl, { 
          method: 'DELETE' 
        }).catch((error) => {
          console.error('删除旧图片时出错:', error);
          // 这里我们不阻止流程继续，即使删除失败
        });
      } catch (error) {
        console.error('删除旧图片时出错:', error);
      }
    }
  };
  
  /**
   * 阻止事件冒泡的处理函数
   */
  const stopPropagation = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  /**
   * 处理品牌选择变更
   */
  const handleBrandChange = (value: string) => {
    if (!isOpen) return;
    
    // 更新表单数据
    setFormData(prev => ({
      ...prev,
      brandId: Number(value)
    }));

    // 找到对应的品牌名称
    const brand = brands.find(b => b.id.toString() === value);
    const brandName = brand ? brand.name : '';
    setSelectedBrandName(brandName);

    // 更新产品名称
    updateProductName(brandName, selectedCategoryName);
  };

  /**
   * 处理品类选择变更
   */
  const handleCategoryChange = (value: string) => {
    if (!isOpen) return;
    
    // 更新表单数据
    setFormData(prev => ({
      ...prev,
      categoryId: Number(value)
    }));

    // 找到对应的品类名称
    const category = categories.find(c => c.id.toString() === value);
    const categoryName = category ? category.name : '';
    setSelectedCategoryName(categoryName);

    // 更新产品名称
    updateProductName(selectedBrandName, categoryName);
  };

  /**
   * 更新产品名称
   */
  const updateProductName = (brandName: string, categoryName: string) => {
    if (!isOpen || !isAutoNameEnabled) return;

    // 构建前缀
    const prefix = `${brandName}${categoryName}`;
    
    // 如果有自定义部分，保留它，否则只显示前缀
    const newName = prefix + customNamePart;
    
    // 标记当前是通过程序更新表单，避免触发循环
    setIsUpdatingFormName(true);
    
    // 使用单一更新方式，避免重复触发更新
    setFormData(prev => ({
      ...prev,
      name: newName
    }));
    
    // 使用setTimeout确保状态更新后再设置表单值
    setTimeout(() => {
      form.setFieldValue('name', newName);
      
      // 在下一个事件循环中重置标记
      setTimeout(() => {
        setIsUpdatingFormName(false);
      }, 0);
    }, 0);
  };

  /**
   * 处理产品名称变更
   */
  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 如果当前是通过程序更新表单，不再处理onChange事件
    if (isUpdatingFormName || !isOpen) return;
    
    const fullName = e.target.value;
    
    // 从全名中提取自定义部分（去掉前缀）
    const prefix = `${selectedBrandName}${selectedCategoryName}`;
    const newCustomPart = prefix && fullName.startsWith(prefix) 
      ? fullName.substring(prefix.length)
      : fullName;
    
    // 保存自定义部分
    setCustomNamePart(newCustomPart);
    
    // 更新表单数据
    setFormData(prev => ({
      ...prev,
      name: fullName
    }));
  };

  /**
   * 切换自动命名功能
   */
  const toggleAutoName = () => {
    setIsAutoNameEnabled(!isAutoNameEnabled);
  };

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    try {
      if (!isOpen) return;
      
      const values = await form.validateFields();
      
      // 将表单值与formData合并，确保aliases等特殊字段正确处理
      const submitData = {
        ...values,
        aliases: formData.aliases,
        cost: formData.cost
      };
      
      setIsSubmitting(true);
      setError(null);
      
      let response;
      
      if (isEditing && product) {
        // 更新产品
        response = await fetch(`/api/team/${teamCode}/products/${product.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submitData)
        });
      } else {
        // 创建产品
        response = await fetch(`/api/team/${teamCode}/products`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submitData)
        });
      }
      
      // 处理响应
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.error || '操作失败');
      }
      
      // 成功处理
      onSuccess();
      onClose();
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError('表单验证失败，请检查输入');
      }
    } finally {
      setIsSubmitting(false);
    }
  };
  
  /**
   * 处理关闭模态框
   */
  const handleModalClose = () => {
    form.resetFields();
    onClose();
  };
  
  // 定义模态框的页脚
  const modalFooter = (
    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
      <Button onClick={handleModalClose}>
        取消
      </Button>
      <Button
        type="primary"
        onClick={() => form.submit()}
        loading={isSubmitting}
      >
        {isEditing ? '保存' : '创建'}
      </Button>
    </div>
  );
  
  if (!isOpen) {
    return null;
  }
  
  return (
    <Modal
      open={isOpen}
      title={isEditing ? '编辑产品' : '添加产品'}
      onCancel={handleModalClose}
      footer={modalFooter}
      width="90%"
      maskClosable={false}
      style={{ top: 20 }}
      styles={{
        body: { 
          padding: '16px',
          maxHeight: 'calc(100vh - 200px)',
          overflowY: 'hidden',
          height: 'auto'
        },
        content: {
          maxWidth: '100%'
        }
      }}
      destroyOnHidden={true}
    >
      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          closable
          className="mb-4"
          style={{ marginBottom: '16px' }}
        />
      )}
      
      <Form
        form={form}
        layout="vertical"
        initialValues={formData}
        onFinish={handleSubmit}
        className="product-form"
        preserve={false}
        name="productForm"
        style={{ overflowX: 'hidden' }}
      >
        <Row gutter={16} style={{ margin: 0 }}>
          {/* 左侧：基本信息和其他字段 */}
          <Col span={18} style={{ paddingLeft: 0 }}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              {/* 基本信息区域 */}
              <Card title="基本信息" variant="outlined" styles={{ 
                body: { 
                  padding: '16px'
                } 
              }}>
                <Row gutter={16}>
                  {/* 产品名称 */}
                  <Col span={12}>
                    <Form.Item
                      name="name"
                      label={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <span style={{ marginRight: '8px' }}>产品名称</span>
                          <Switch
                            size="small"
                            checked={isAutoNameEnabled}
                            onChange={toggleAutoName}
                            checkedChildren="自动"
                            unCheckedChildren="手动"
                          />
                        </div>
                      }
                      rules={[{ required: true, message: '请输入产品名称' }]}
                    >
                      <Input placeholder="请输入产品名称" onChange={handleNameChange} />
                    </Form.Item>
                  </Col>
                  
                  {/* SKU */}
                  <Col span={6}>
                    <Form.Item
                      name="sku"
                      label="SKU"
                    >
                      <Input placeholder="请输入SKU" />
                    </Form.Item>
                  </Col>
                  
                  {/* 产品代码 */}
                  <Col span={6}>
                    <Form.Item
                      name="code"
                      label="产品代码"
                    >
                      <Input placeholder="请输入产品代码" />
                    </Form.Item>
                  </Col>
                </Row>
                
                <Row gutter={16}>
                  {/* 产品级别 */}
                  <Col span={6}>
                    <Form.Item
                      name="level"
                      label="产品级别"
                    >
                      <Input placeholder="请输入产品级别" />
                    </Form.Item>
                  </Col>
                  
                  {/* 产品别名 */}
                  <Col span={18}>
                    <Form.Item
                      label="产品别名"
                      name="aliases"
                    >
                      <div onClick={stopPropagation} style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', padding: '4px 0' }}>
                        {formData.aliases?.map((alias, index) => {
                          if (editInputIndex === index) {
                            return (
                              <Input
                                ref={editInputRef}
                                key={alias}
                                size="small"
                                value={editInputValue}
                                onChange={handleEditInputChange}
                                onBlur={handleEditInputConfirm}
                                onPressEnter={handleEditInputConfirm}
                                style={{ width: '100px' }}
                              />
                            );
                          }
                          return (
                            <Tag
                              key={alias}
                              closable
                              style={{ userSelect: 'none', cursor: 'pointer' }}
                              onClose={() => handleRemoveAlias(index)}
                              onClick={() => startEdit(index)}
                            >
                              {alias}
                            </Tag>
                          );
                        })}
                        {inputVisible ? (
                          <Input
                            ref={inputRef}
                            type="text"
                            size="small"
                            style={{ width: '100px' }}
                            value={aliasInput}
                            onChange={handleInputChange}
                            onBlur={handleInputConfirm}
                            onPressEnter={handleInputConfirm}
                          />
                        ) : (
                          <Tag 
                            onClick={showInput} 
                            style={{ 
                              background: '#fff', 
                              borderStyle: 'dashed',
                              cursor: 'pointer'
                            }}
                          >
                            <PlusOutlined /> 添加别名
                          </Tag>
                        )}
                      </div>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              {/* 关联信息 */}
              <Card title="关联信息" variant="outlined" styles={{ 
                body: { 
                  padding: '16px'
                } 
              }}>
                <Row gutter={16}>
                  {/* 供应商 */}
                  <Col span={8}>
                    <Form.Item
                      name="supplierId"
                      label="供应商"
                      rules={[{ required: true, message: '请选择供应商' }]}
                    >
                      <Select
                        placeholder="请选择供应商"
                        showSearch
                        filterOption={(input, option) => 
                          (option?.label as string).toLowerCase().includes(input.toLowerCase())
                        }
                        options={suppliers.map(supplier => ({ 
                          label: supplier.name, 
                          value: supplier.id.toString()
                        }))}
                        getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        onClick={stopPropagation}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 品牌 */}
                  <Col span={8}>
                    <Form.Item
                      name="brandId"
                      label="品牌"
                      rules={[{ required: true, message: '请选择品牌' }]}
                    >
                      <Select
                        placeholder="请选择品牌"
                        showSearch
                        filterOption={(input, option) => 
                          (option?.label as string).toLowerCase().includes(input.toLowerCase())
                        }
                        options={brands.map(brand => ({ 
                          label: brand.name, 
                          value: brand.id.toString()
                        }))}
                        getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        onClick={stopPropagation}
                        onChange={handleBrandChange}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 品类 */}
                  <Col span={8}>
                    <Form.Item
                      name="categoryId"
                      label="品类"
                      rules={[{ required: true, message: '请选择品类' }]}
                    >
                      <Select
                        placeholder="请选择品类"
                        showSearch
                        filterOption={(input, option) => 
                          (option?.label as string).toLowerCase().includes(input.toLowerCase())
                        }
                        options={categories.map(category => ({ 
                          label: category.name, 
                          value: category.id.toString()
                        }))}
                        getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        onClick={stopPropagation}
                        onChange={handleCategoryChange}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              {/* 价格和库存 */}
              <Card title="价格和库存" variant="outlined" styles={{ 
                body: { 
                  padding: '16px'
                } 
              }}>
                <Row gutter={16}>
                  {/* 售价 */}
                  <Col xs={12} sm={8} md={6} lg={4}>
                    <Form.Item
                      name="price"
                      label="售价"
                      rules={[{ required: true, message: '请输入售价' }]}
                    >
                      <InputNumber
                        min={0}
                        step={0.01}
                        precision={2}
                        prefix="¥"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 成本价 */}
                  <Col xs={12} sm={8} md={6} lg={4}>
                    <Form.Item
                      label="成本价"
                      name={['cost', 'costPrice']}
                    >
                      <InputNumber
                        min={0}
                        step={0.01}
                        precision={2}
                        prefix="¥"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 包装费 */}
                  <Col xs={12} sm={8} md={6} lg={4}>
                    <Form.Item
                      label="包装费"
                      name={['cost', 'packagingFee']}
                    >
                      <InputNumber
                        min={0}
                        step={0.01}
                        precision={2}
                        prefix="¥"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 运费 */}
                  <Col xs={12} sm={8} md={6} lg={4}>
                    <Form.Item
                      label="运费"
                      name={['cost', 'shippingFee']}
                    >
                      <InputNumber
                        min={0}
                        step={0.01}
                        precision={2}
                        prefix="¥"
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                  
                  {/* 库存 */}
                  <Col xs={12} sm={8} md={6} lg={4}>
                    <Form.Item
                      name="stock"
                      label="库存数量"
                    >
                      <InputNumber
                        min={0}
                        precision={0}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
            </Space>
          </Col>
          
          {/* 右侧: 图片 */}
          <Col span={6} style={{ paddingRight: 0 }}>
            <Card title="产品图片" variant="outlined" styles={{ body: { padding: '16px' } }}>
              {/* 上传组件 */}
              <div>
                <UploadImage 
                  onSuccess={handleImageUploadSuccess}
                  folder="products"
                />
              </div>
              
              {/* 手动输入图片URL */}
              <Form.Item
                name="image"
                label="图片URL"
                extra={<>输入图片URL或<span style={{ color: '#ff4d4f' }}>使用上方上传组件</span>自动生成</>}
                rules={[{ required: true, message: '请上传产品图片或提供图片URL' }]}
              >
                <Input placeholder="http://example.com/image.jpg" />
              </Form.Item>
            </Card>
            
            {/* 产品描述 - 移动到右侧图片下方 */}
            <Card title="产品描述" variant="outlined" style={{ marginTop: '16px' }} styles={{ body: { padding: '16px' } }}>
              <Form.Item
                name="description"
                noStyle
              >
                <TextArea
                  rows={4}
                  placeholder="请输入产品描述"
                />
              </Form.Item>
            </Card>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
} 