/**
 * 销售记录发货模态框组件
 * 作者: 阿瑞
 * 功能: 提供销售记录的发货信息录入界面
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useCallback, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Modal from '@/components/ui/Modal';
import { useNotification } from '@/components/ui/Notification';
import { useTheme } from '@/hooks';
import { SalesRecord } from '@/models/team/types/old/sales';
import { MdLocalShipping, MdPerson, MdPhone, MdShoppingCart, MdArticle } from 'react-icons/md';

/**
 * 扩展的销售记录接口，使用与页面一致的类型
 */
interface SalesRecordWithDetails extends Omit<SalesRecord, 'products'> {
  products?: {
    productId: number;
    productName?: string;
    productCode?: string;
    price: number;
    quantity: number;
    brandName?: string;
    categoryName?: string;
    supplierName?: string;
    image?: string;
  }[];
  // 客户信息
  customerName?: string;
  customerPhone?: string;
  customerFollowDate?: string;
  customerAddress?: string;
  // 其他信息省略...
}

// 定义物流记录产品的接口
interface LogisticsProductItem {
  product_id: number;
  quantity: number;
}

/**
 * 物流记录接口
 */
interface LogisticsRecord {
  id: number;
  tracking_number: string;
  is_queryable: boolean;
  customer_tail_number: string;
  company: string;
  status?: string;
  record_id: number;
  record_type: string;
  created_at: string;
  updated_at: string;
  products?: LogisticsProductItem[];
}

/**
 * 物流公司选项
 */
const LOGISTICS_COMPANIES = [
  { value: '顺丰速运', label: '顺丰速运' },
  { value: '中通快递', label: '中通快递' },
  { value: '圆通速递', label: '圆通速递' },
  { value: '韵达快递', label: '韵达快递' },
  { value: '申通快递', label: '申通快递' },
  { value: '百世快递', label: '百世快递' },
  { value: 'EMS', label: 'EMS' },
  { value: '京东物流', label: '京东物流' },
  { value: '天天快递', label: '天天快递' },
  { value: '邮政快递包裹', label: '邮政快递包裹' },
  { value: '其他', label: '其他' }
];

/**
 * 物流记录表单数据接口
 */
interface LogisticsFormData {
  trackingNumber: string;
  company: string;
  customerTailNumber: string;
  isQueryable: boolean;
  selectedProducts: {
    productId: number;
    quantity: number;
  }[];
}

/**
 * 组件Props接口
 */
interface ShipModalProps {
  isOpen: boolean;
  onClose: () => void;
  salesRecord: SalesRecordWithDetails;
}

/**
 * 格式化金额显示
 */
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined || amount === null) return '¥0.00';
  return `¥${Number(amount).toFixed(2)}`;
};

/**
 * 销售记录发货模态框组件
 */
const ShipModal: React.FC<ShipModalProps> = ({
  isOpen,
  onClose,
  salesRecord
}) => {
  const notification = useNotification();
  const params = useParams();
  const teamCode = params?.teamCode as string;
  const { isDarkMode } = useTheme();

  // 物流记录加载状态
  const [isCheckingLogistics, setIsCheckingLogistics] = useState(false);
  const [existingLogistics, setExistingLogistics] = useState<LogisticsRecord | null>(null);
  const [modalTitle, setModalTitle] = useState("发货处理");

  // 提取客户手机尾号
  const getCustomerTailNumber = useCallback(() => {
    if (!salesRecord.customerPhone) return '';
    if (salesRecord.customerPhone.length >= 4) {
      return salesRecord.customerPhone.slice(-4);
    }
    return salesRecord.customerPhone;
  }, [salesRecord.customerPhone]);

  // 物流表单状态
  const [formData, setFormData] = useState<LogisticsFormData>({
    trackingNumber: '',
    company: LOGISTICS_COMPANIES[0].value,
    customerTailNumber: getCustomerTailNumber(),
    isQueryable: true,
    selectedProducts: salesRecord.products 
      ? salesRecord.products.map(p => ({ productId: p.productId, quantity: p.quantity }))
      : []
  });

  // 表单错误状态
  const [errors, setErrors] = useState({
    trackingNumber: '',
    company: '',
    customerTailNumber: ''
  });

  // 加载状态
  const [isLoading, setIsLoading] = useState(false);

  /**
   * 检查是否已有物流记录
   */
  const checkExistingLogistics = useCallback(async () => {
    if (!isOpen || !salesRecord.id) return;

    setIsCheckingLogistics(true);
    try {
      const response = await fetch(`/api/team/${teamCode}/logistics?recordId=${salesRecord.id}&recordType=SalesRecord`);
      
      if (response.ok) {
        const data = await response.json();
        if (data.records && data.records.length > 0) {
          setExistingLogistics(data.records[0]);
          setModalTitle("编辑物流信息");
          
          // 填充表单数据
          const logistics = data.records[0];
          setFormData({
            trackingNumber: logistics.tracking_number || '',
            company: logistics.company || LOGISTICS_COMPANIES[0].value,
            customerTailNumber: logistics.customer_tail_number || getCustomerTailNumber(),
            isQueryable: logistics.is_queryable !== undefined ? logistics.is_queryable : true,
            selectedProducts: logistics.products 
              ? logistics.products.map((p: LogisticsProductItem) => ({ 
                  productId: p.product_id, 
                  quantity: p.quantity 
                }))
              : salesRecord.products 
                ? salesRecord.products.map(p => ({ productId: p.productId, quantity: p.quantity }))
                : []
          });
        } else {
          setExistingLogistics(null);
          setModalTitle("发货处理");
          
          // 重置表单
          setFormData({
            trackingNumber: '',
            company: LOGISTICS_COMPANIES[0].value,
            customerTailNumber: getCustomerTailNumber(),
            isQueryable: true,
            selectedProducts: salesRecord.products 
              ? salesRecord.products.map(p => ({ productId: p.productId, quantity: p.quantity }))
              : []
          });
        }
      }
    } catch (error) {
      console.error('检查物流记录失败:', error);
    } finally {
      setIsCheckingLogistics(false);
    }
  }, [isOpen, salesRecord, teamCode, getCustomerTailNumber]);

  // 当模态框打开时检查是否已有物流记录
  useEffect(() => {
    if (isOpen) {
      checkExistingLogistics();
    }
  }, [isOpen, checkExistingLogistics]);

  /**
   * 处理表单字段变更
   */
  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    
    if (type === 'checkbox') {
      const checkbox = e.target as HTMLInputElement;
      setFormData(prev => ({
        ...prev,
        [name]: checkbox.checked
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    }

    // 清除错误
    if (name in errors) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  /**
   * 处理产品数量变更
   */
  const handleProductQuantityChange = (productId: number, quantity: number) => {
    setFormData(prev => ({
      ...prev,
      selectedProducts: prev.selectedProducts.map(p => 
        p.productId === productId ? { ...p, quantity } : p
      )
    }));
  };

  /**
   * 处理表单验证
   */
  const validateForm = (): boolean => {
    const newErrors = {
      trackingNumber: '',
      company: '',
      customerTailNumber: ''
    };

    if (!formData.trackingNumber.trim()) {
      newErrors.trackingNumber = '请输入物流单号';
    }

    if (!formData.company) {
      newErrors.company = '请选择物流公司';
    }

    if (!formData.customerTailNumber) {
      newErrors.customerTailNumber = '请输入客户手机尾号';
    } else if (!/^\d{4}$/.test(formData.customerTailNumber)) {
      newErrors.customerTailNumber = '尾号必须是4位数字';
    }

    setErrors(newErrors);
    return !Object.values(newErrors).some(error => error);
  };

  /**
   * 处理提交发货信息
   */
  const handleSubmit = async () => {
    if (!validateForm()) return;

    setIsLoading(true);

    try {
      // 构建请求数据
      const requestData = {
        salesRecordId: salesRecord.id,
        trackingNumber: formData.trackingNumber,
        company: formData.company,
        customerTailNumber: formData.customerTailNumber,
        isQueryable: formData.isQueryable,
        products: formData.selectedProducts
      };

      // 发送API请求
      const response = await fetch(`/api/team/${teamCode}/logistics`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error('发货失败，请稍后重试');
      }

      const data = await response.json();
      notification.success(data.message || '物流信息已成功记录', {
        duration: 3000
      });

      // 关闭模态框
      onClose();
    } catch (error) {
      console.error('提交发货信息失败:', error);
      notification.error(error instanceof Error ? error.message : '发货失败，请稍后重试', {
        duration: 4000
      });
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 渲染产品列表
   */
  const renderProductsList = () => {
    if (!salesRecord.products || salesRecord.products.length === 0) {
      return (
        <div className="text-center py-4 text-gray-500 dark:text-gray-400">
          没有产品信息
        </div>
      );
    }

    return (
      <div className="space-y-2 max-h-60 overflow-y-auto pr-2">
        {salesRecord.products.map((product, index) => {
          const selectedProduct = formData.selectedProducts.find(p => p.productId === product.productId);
          const quantity = selectedProduct ? selectedProduct.quantity : 0;

          return (
            <div
              key={index}
              className={`flex items-center p-2 border rounded-md ${
                isDarkMode ? 'border-gray-700 bg-gray-800' : 'border-gray-200 bg-white'
              }`}
            >
              <div className="flex-1">
                <div className="font-medium text-sm">{product.productName || '未命名产品'}</div>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  {product.productCode ? `编码: ${product.productCode}` : ''}
                  {product.brandName ? ` | 品牌: ${product.brandName}` : ''}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  单价: {formatAmount(product.price)}
                </div>
              </div>
              
              <div className="flex items-center">
                <label className="text-sm mr-2">数量:</label>
                <input
                  type="number"
                  min="0"
                  max={product.quantity}
                  value={quantity}
                  onChange={(e) => handleProductQuantityChange(product.productId, parseInt(e.target.value) || 0)}
                  className={`w-16 p-1 text-center border rounded ${
                    isDarkMode 
                      ? 'border-gray-600 bg-gray-700 text-white' 
                      : 'border-gray-300 bg-white text-gray-700'
                  }`}
                />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  /**
   * 渲染模态框底部按钮
   */
  const renderFooter = () => {
    return (
      <div className="flex justify-end space-x-2">
        <button
          type="button"
          onClick={onClose}
          className={`px-4 py-2 text-sm font-medium rounded-md ${
            isDarkMode
              ? 'bg-gray-700 text-gray-200 hover:bg-gray-600'
              : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
          }`}
          disabled={isLoading}
        >
          取消
        </button>
        <button
          type="button"
          onClick={handleSubmit}
          className={`px-4 py-2 text-sm font-medium rounded-md flex items-center ${
            isLoading
              ? 'bg-blue-400 cursor-not-allowed'
              : 'bg-blue-600 hover:bg-blue-700'
          } text-white`}
          disabled={isLoading}
        >
          {isLoading ? (
            '处理中...'
          ) : (
            <>
              {existingLogistics ? '保存修改' : '确认发货'}
            </>
          )}
        </button>
      </div>
    );
  };

  // 显示加载中
  if (isCheckingLogistics) {
    return (
      <Modal
        isOpen={isOpen}
        onClose={onClose}
        title="加载中..."
        footer={null}
        size="lg"
      >
        <div className="flex justify-center items-center p-10">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
        </div>
      </Modal>
    );
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={
        <div className="flex items-center text-lg">
          <MdLocalShipping className="mr-2 text-blue-500" size={22} />
          <span>{modalTitle}</span>
        </div>
      }
      footer={renderFooter()}
      size="lg"
    >
      <div className="space-y-4">
        {/* 客户信息卡片 */}
        <div className={`p-3 rounded-md ${isDarkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
          <div className="flex items-center mb-2">
            <MdPerson className="mr-2 text-blue-500" size={18} />
            <h3 className="font-medium">客户信息</h3>
          </div>
          <div className="grid grid-cols-2 gap-2 text-sm">
            <div>
              <span className="text-gray-500 dark:text-gray-400">姓名: </span>
              <span>{salesRecord.customerName || '-'}</span>
            </div>
            <div className="flex items-center">
              <MdPhone className="mr-1 text-green-500" size={16} />
              <span className="text-gray-500 dark:text-gray-400">电话: </span>
              <span>{salesRecord.customerPhone || '-'}</span>
            </div>
            {salesRecord.customerAddress && (
              <div className="col-span-2">
                <span className="text-gray-500 dark:text-gray-400">地址: </span>
                <span>{salesRecord.customerAddress}</span>
              </div>
            )}
          </div>
        </div>
        
        {/* 发货表单 */}
        <div className={`p-4 rounded-md ${isDarkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
          <div className="flex items-center mb-3">
            <MdLocalShipping className="mr-2 text-green-500" size={18} />
            <h3 className="font-medium">物流信息</h3>
          </div>
          
          <div className="space-y-3">
            <div>
              <label className="flex items-center text-sm font-medium mb-1">
                <MdArticle className="mr-1 text-blue-500" size={16} />
                物流单号 <span className="text-red-500 ml-1">*</span>
              </label>
              <input
                type="text"
                name="trackingNumber"
                value={formData.trackingNumber}
                onChange={handleFormChange}
                placeholder="请输入物流单号"
                className={`w-full p-2 border rounded-md ${
                  isDarkMode 
                    ? 'border-gray-600 bg-gray-700 text-white' 
                    : 'border-gray-300 bg-white text-gray-700'
                } ${errors.trackingNumber ? 'border-red-500' : ''}`}
              />
              {errors.trackingNumber && (
                <p className="mt-1 text-xs text-red-500">{errors.trackingNumber}</p>
              )}
            </div>
            
            <div>
              <label className="block text-sm font-medium mb-1">
                物流公司 <span className="text-red-500">*</span>
              </label>
              <select
                name="company"
                value={formData.company}
                onChange={handleFormChange}
                className={`w-full p-2 border rounded-md ${
                  isDarkMode 
                    ? 'border-gray-600 bg-gray-700 text-white' 
                    : 'border-gray-300 bg-white text-gray-700'
                } ${errors.company ? 'border-red-500' : ''}`}
              >
                {LOGISTICS_COMPANIES.map((company, index) => (
                  <option key={index} value={company.value}>{company.label}</option>
                ))}
              </select>
              {errors.company && (
                <p className="mt-1 text-xs text-red-500">{errors.company}</p>
              )}
            </div>
            
            <div>
              <label className="flex items-center text-sm font-medium mb-1">
                <MdPhone className="mr-1 text-purple-500" size={16} />
                客户手机尾号 <span className="text-red-500 ml-1">*</span>
              </label>
              <input
                type="text"
                name="customerTailNumber"
                value={formData.customerTailNumber}
                onChange={handleFormChange}
                placeholder="请输入客户手机尾号(后4位)"
                maxLength={4}
                className={`w-full p-2 border rounded-md ${
                  isDarkMode 
                    ? 'border-gray-600 bg-gray-700 text-white' 
                    : 'border-gray-300 bg-white text-gray-700'
                } ${errors.customerTailNumber ? 'border-red-500' : ''}`}
              />
              {errors.customerTailNumber && (
                <p className="mt-1 text-xs text-red-500">{errors.customerTailNumber}</p>
              )}
            </div>
            
            <div className="flex items-center">
              <input
                type="checkbox"
                id="isQueryable"
                name="isQueryable"
                checked={formData.isQueryable}
                onChange={handleFormChange}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
              />
              <label htmlFor="isQueryable" className="ml-2 flex items-center text-sm">
                查询物流
              </label>
            </div>
          </div>
        </div>
        
        {/* 产品列表 */}
        <div className={`p-4 rounded-md ${isDarkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
          <div className="flex items-center mb-3">
            <MdShoppingCart className="mr-2 text-purple-500" size={18} />
            <h3 className="font-medium">发货产品</h3>
          </div>
          {renderProductsList()}
        </div>
      </div>
    </Modal>
  );
};

export default ShipModal;
