/**
 * 创建销售记录页面
 * 作者: 阿瑞
 * 功能: 提供创建销售记录数据的功能，目前仅做示例数据
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useEffect } from 'react';
import { useTheme } from '@/hooks';
import { useTeam } from '@/hooks/useTeam';
import { MdShoppingCart, MdAdd, MdPerson, MdLocalShipping, MdAddCircleOutline, MdDelete } from 'react-icons/md';
//从@/utils导入所有工具
// 导入UI组件
import Card from '@/components/ui/Card';
// 导入自定义组件
import CustomerSelector, { Customer } from './components/CustomerSelector';
import ProductSelector, { Product } from './components/ProductSelector';
import CustomerModal from './components/AddCustomer';

interface SelectedProductItem {
  product: Product;
  quantity: number;
  price: number;
}

enum PaymentType {
  FULL_PAYMENT = 0, // 全款
  DEPOSIT = 1,      // 定金
  UNPAID = 2,       // 未付
  FREE = 3,         // 赠送
  OTHER = 4         // 其他
}

interface SalesFormData {
  customerId: number | null;
  products: SelectedProductItem[];
  dealDate: string;
  paymentType?: PaymentType;
  platformId?: number;
  receivable: number;
  received: number;
  pending: number;
  dealShopId?: number;
  remark?: string;
}

/**
 * 已选产品列表组件
 * 显示已添加到销售记录的产品
 */
const SelectedProductList = ({ 
  products, 
  onRemove 
}: { 
  products: SelectedProductItem[], 
  onRemove: (index: number) => void 
}) => {
  const { isDarkMode } = useTheme();
  
  if (products.length === 0) {
    return null;
  }
  
  return (
    <div className="overflow-x-auto">
      <table className="min-w-full">
        <thead>
          <tr className={`${isDarkMode ? 'text-gray-300' : 'text-gray-700'} text-sm border-b border-gray-200 dark:border-gray-700`}>
            <th className="text-left px-2 py-1.5">产品名称</th>
            <th className="text-right px-2 py-1.5">单价</th>
            <th className="text-right px-2 py-1.5">数量</th>
            <th className="text-right px-2 py-1.5">金额</th>
            <th className="text-center px-2 py-1.5">操作</th>
          </tr>
        </thead>
        <tbody>
          {products.map((item, index) => (
            <tr 
              key={`${item.product.id}-${index}`} 
              className={`border-b ${isDarkMode ? 'border-gray-700 hover:bg-gray-800/50' : 'border-gray-100 hover:bg-gray-50'} text-sm`}
            >
              <td className="px-2 py-2">{item.product.name}</td>
              <td className="text-right px-2 py-2">¥{item.price.toFixed(2)}</td>
              <td className="text-right px-2 py-2">{item.quantity}</td>
              <td className="text-right px-2 py-2 font-medium">¥{(item.price * item.quantity).toFixed(2)}</td>
              <td className="text-center px-2 py-2">
                <button 
                  type="button"
                  onClick={() => onRemove(index)}
                  className={`inline-flex items-center p-1 rounded-full
                    ${isDarkMode 
                      ? 'text-red-300 hover:bg-red-900/40 hover:text-red-200' 
                      : 'text-red-500 hover:bg-red-50 hover:text-red-700'}`}
                >
                  <MdDelete size={18} />
                </button>
              </td>
            </tr>
          ))}
          <tr className={`font-medium ${isDarkMode ? 'text-white bg-slate-800/70' : 'text-gray-800 bg-gray-50'}`}>
            <td className="px-2 py-2">总计</td>
            <td className="px-2 py-2"></td>
            <td className="text-right px-2 py-2">{products.reduce((sum, item) => sum + item.quantity, 0)}</td>
            <td className="text-right px-2 py-2">¥{products.reduce((sum, item) => sum + (item.price * item.quantity), 0).toFixed(2)}</td>
            <td className="px-2 py-2"></td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

/**
 * 销售记录页面组件
 * 展示销售记录列表和创建销售记录功能
 */
export default function SalesPage() {
  // 获取路由参数和团队信息
  const { isDarkMode } = useTheme();
  const { currentTeam } = useTeam();
  const teamCode = currentTeam?.team_code || '';
  
  // 页面状态管理
  const [isPageLoading, setIsPageLoading] = useState(true);
  const [error] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // 客户和产品选择状态
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [productQuantity, setProductQuantity] = useState<number>(1);
  const [productPrice, setProductPrice] = useState<number>(0);
  
  // 客户模态框状态
  const [isCustomerModalOpen, setIsCustomerModalOpen] = useState(false);
  
  // 表单数据
  const [formData, setFormData] = useState<SalesFormData>({
    customerId: null,
    products: [],
    dealDate: new Date().toISOString().slice(0, 10), // 当前日期
    receivable: 0,
    received: 0,
    pending: 0
  });
  
  // 模拟支付平台
  const [platforms] = useState([
    { id: 1, name: "微信支付" },
    { id: 2, name: "支付宝" },
    { id: 3, name: "银行转账" }
  ]);
  
  // 模拟店铺
  const [shops] = useState([
    { id: 1, nickname: "官方旗舰店", wechat: "shop1" },
    { id: 2, nickname: "直营店", wechat: "shop2" }
  ]);
  
  // 选择客户处理函数
  const handleSelectCustomer = (customer: Customer) => {
    setSelectedCustomer(customer);
    setFormData(prev => ({...prev, customerId: customer.id}));
  };
  
  // 处理创建新客户
  const handleCreateCustomer = () => {
    // 打开新建客户模态框
    setIsCustomerModalOpen(true);
  };
  
  // 客户模态框成功回调
  const handleCustomerSuccess = () => {
    // 刷新客户列表
    // TODO: 实现刷新客户列表的逻辑
  };
  
  // 选择产品处理函数
  const handleSelectProduct = (product: Product) => {
    setSelectedProduct(product);
    setProductPrice(product.price);
  };
  
  // 添加产品到表单
  const handleAddProduct = () => {
    if (!selectedProduct) return;
    
    const newProduct: SelectedProductItem = {
      product: selectedProduct,
      quantity: productQuantity,
      price: productPrice
    };
    
    // 计算新的总额
    
    setFormData(prev => {
      const updatedProducts = [...prev.products, newProduct];
      const newReceivable = updatedProducts.reduce((total, item) => 
        total + (item.quantity * item.price), 0);
      
      return {
        ...prev,
        products: updatedProducts,
        receivable: newReceivable,
        received: newReceivable, // 默认实收等于应收
        pending: 0 // 默认待收为0
      };
    });
    
    // 重置选择
    setSelectedProduct(null);
    setProductQuantity(1);
  };
  
  // 移除已选产品
  const handleRemoveProduct = (index: number) => {
    setFormData(prev => {
      const updatedProducts = [...prev.products];
      updatedProducts.splice(index, 1);
      
      const newReceivable = updatedProducts.reduce((total, item) => 
        total + (item.quantity * item.price), 0);
      
      return {
        ...prev,
        products: updatedProducts,
        receivable: newReceivable,
        received: newReceivable,
        pending: 0
      };
    });
  };
  
  // 处理表单输入变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    setFormData(prev => {
      const updated = {...prev, [name]: value};
      
      // 如果修改了应收或实收，自动计算待收
      if (name === 'receivable' || name === 'received') {
        const receivable = name === 'receivable' ? parseFloat(value) || 0 : prev.receivable;
        const received = name === 'received' ? parseFloat(value) || 0 : prev.received;
        updated.pending = Math.max(0, receivable - received);
      }
      
      return updated;
    });
  };
  
  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // 这里应该添加表单验证
    
    setIsSubmitting(true);
    
    // 模拟API请求
    setTimeout(() => {
      setSuccessMessage('销售记录创建成功！');
      setIsSubmitting(false);
      
      // 重置表单
      setFormData({
        customerId: null,
        products: [],
        dealDate: new Date().toISOString().slice(0, 10),
        receivable: 0,
        received: 0,
        pending: 0
      });
      setSelectedCustomer(null);
    }, 1500);
  };
  
  // 支付类型选项渲染
  const renderPaymentTypeOptions = () => {
    return (
      <>
        <option value="">请选择收款类型</option>
        <option value={PaymentType.FULL_PAYMENT}>全款</option>
        <option value={PaymentType.DEPOSIT}>定金</option>
        <option value={PaymentType.UNPAID}>未付</option>
        <option value={PaymentType.FREE}>赠送</option>
        <option value={PaymentType.OTHER}>其他</option>
      </>
    );
  };
  
  // 获取支付类型颜色
  
  // 数据加载模拟
  useEffect(() => {
    // 模拟数据加载
    const timer = setTimeout(() => {
      setIsPageLoading(false);
    }, 1000);
    
    return () => clearTimeout(timer);
  }, []);

  return (
    <div className="w-full mb-10">
      {/* 页面标题 */}
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center">
          <MdShoppingCart className="mr-2 text-blue-500" size={24} />
          销售记录
        </h1>
      </div>

      {/* 客户模态框 */}
      <CustomerModal
        isOpen={isCustomerModalOpen}
        onClose={() => setIsCustomerModalOpen(false)}
        onSuccess={handleCustomerSuccess}
        teamCode={teamCode}
      />

      {/* 加载状态显示 */}
      {isPageLoading ? (
        <Card
          padding="large"
          className="flex justify-center items-center py-20"
          isLoading={true}
          loadingText="正在加载数据..."
        >
          <div></div>
        </Card>
      ) : (
        <>
          {/* 成功消息 */}
          {successMessage && (
            <div className={`
              mb-4 p-3 rounded-lg border-l-4 border-green-500 
              ${isDarkMode ? 'bg-green-900/20' : 'bg-green-50'} 
              text-green-700 dark:text-green-300
            `}>
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
                <p>{successMessage}</p>
              </div>
            </div>
          )}

          {/* 错误提示 */}
          {error && (
            <div className={`
              mb-4 p-3 rounded-lg border-l-4 border-red-500 
              ${isDarkMode ? 'bg-red-900/20' : 'bg-red-50'} 
              text-red-700 dark:text-red-300
            `}>
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <p>{error}</p>
              </div>
            </div>
          )}

          <form onSubmit={handleSubmit}>
            {/* 主要内容区域 */}
            <div className="space-y-4">
              {/* 上部分 - 客户与产品选择 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* 左侧栏 - 客户选择 */}
                <Card
                  padding="medium"
                  title={
                    <div className="flex items-center">
                      <MdPerson className="mr-1.5 text-blue-500" />
                      <span>客户选择</span>
                    </div>
                  }
                >
                  <CustomerSelector
                    selectedCustomer={selectedCustomer}
                    onSelectCustomer={handleSelectCustomer}
                    teamCode={teamCode}
                    onCreateCustomer={handleCreateCustomer}
                  />
                </Card>

                {/* 右侧栏 - 产品选择 */}
                <Card
                  padding="medium"
                  title={
                    <div className="flex items-center justify-between w-full">
                      <div className="flex items-center">
                        <MdLocalShipping className="mr-1.5 text-blue-500" />
                        <span>产品选择</span>
                      </div>
                      <button
                        type="button"
                        className={`
                          px-2 py-1 rounded-md text-xs
                          flex items-center 
                          ${isDarkMode
                            ? 'bg-green-600/70 hover:bg-green-500/70 text-white'
                            : 'bg-green-100 hover:bg-green-200 text-green-700'}
                          transition-colors duration-200
                        `}
                      >
                        <MdAddCircleOutline className="mr-1" size={16} />
                        新建产品
                      </button>
                    </div>
                  }
                >
                  <ProductSelector
                    selectedProduct={selectedProduct}
                    onSelectProduct={handleSelectProduct}
                    productPrice={productPrice}
                    onPriceChange={setProductPrice}
                    productQuantity={productQuantity}
                    onQuantityChange={setProductQuantity}
                  />
                  
                  <button
                    type="button"
                    onClick={handleAddProduct}
                    disabled={!selectedProduct}
                    className={`
                      w-full px-4 py-2 rounded-lg text-white font-medium mt-3
                      flex items-center justify-center
                      transition-all duration-200
                      ${selectedProduct
                        ? `${isDarkMode ? 'bg-blue-600/80 hover:bg-blue-500/80' : 'bg-blue-500 hover:bg-blue-600'} 
                          hover:shadow-md hover:scale-[1.02] active:scale-[0.98]`
                        : 'bg-gray-400 cursor-not-allowed'
                      }
                      backdrop-blur-md border border-white/20
                    `}
                  >
                    <MdAdd className="mr-1.5" size={18} />
                    添加产品
                  </button>
                </Card>
              </div>
              
              {/* 产品列表部分 - 仅在有产品时显示 */}
              {formData.products.length > 0 && (
                <div className="mb-4">
                  <Card
                    padding="small"
                    title="已选产品"
                  >
                    <SelectedProductList
                      products={formData.products}
                      onRemove={handleRemoveProduct}
                    />
                  </Card>
                </div>
              )}
              
              {/* 订单详细信息 */}
              <Card
                padding="medium"
                title="订单详细信息"
              >
                <div className="grid grid-cols-1 md:grid-cols-4 gap-x-6 gap-y-4">
                  {/* 第一列 */}
                  <div className="space-y-3">
                    {/* 成交店铺 */}
                    <div>
                      <label htmlFor="dealShopId" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        成交店铺
                      </label>
                      <select
                        id="dealShopId"
                        name="dealShopId"
                        value={formData.dealShopId || ''}
                        onChange={handleChange}
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                        `}
                      >
                        <option value="">请选择成交店铺</option>
                        {shops.map(shop => (
                          <option key={shop.id} value={shop.id}>
                            {shop.nickname || shop.wechat || `店铺ID: ${shop.id}`}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 成交日期 */}
                    <div>
                      <label htmlFor="dealDate" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        成交日期 <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="date"
                        id="dealDate"
                        name="dealDate"
                        value={formData.dealDate}
                        onChange={handleChange}
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                        `}
                        required
                      />
                    </div>
                  </div>

                  {/* 第二列 */}
                  <div className="space-y-3">
                    {/* 收款类型 */}
                    <div>
                      <label htmlFor="paymentType" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        收款类型 <span className="text-red-500">*</span>
                      </label>
                      <div className="relative">
                        <select
                          id="paymentType"
                          name="paymentType"
                          value={formData.paymentType === undefined ? '' : formData.paymentType}
                          onChange={handleChange}
                          className={`                            w-full pl-3 pr-10 py-1.5 rounded-md text-sm appearance-none
                            ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                            backdrop-blur-sm border border-white/20 dark:border-white/10
                            focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                            text-gray-800 dark:text-white
                          `}
                          required
                        >
                          {renderPaymentTypeOptions()}
                        </select>
                      </div>
                    </div>

                    {/* 支付平台 */}
                    <div>
                      <label htmlFor="platformId" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        支付平台 <span className="text-red-500">*</span>
                      </label>
                      <select
                        id="platformId"
                        name="platformId"
                        value={formData.platformId || ''}
                        onChange={handleChange}
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                        `}
                        required
                      >
                        <option value="">请选择支付平台</option>
                        {platforms.map(platform => (
                          <option key={platform.id} value={platform.id}>
                            {platform.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  {/* 第三列 */}
                  <div className="space-y-3">
                    {/* 金额信息 */}
                    <div>
                      <label htmlFor="receivable" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        应收金额 <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="number"
                        id="receivable"
                        name="receivable"
                        value={formData.receivable}
                        onChange={handleChange}
                        step="0.01"
                        min="0"
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                        `}
                        required
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label htmlFor="received" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                          实收金额 <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="number"
                          id="received"
                          name="received"
                          value={formData.received}
                          onChange={handleChange}
                          step="0.01"
                          min="0"
                          className={`
                            w-full px-3 py-1.5 rounded-md text-sm
                            ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                            backdrop-blur-sm border border-white/20 dark:border-white/10
                            focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                            text-gray-800 dark:text-white
                          `}
                          required
                        />
                      </div>

                      <div>
                        <label htmlFor="pending" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                          待收金额
                        </label>
                        <input
                          type="number"
                          id="pending"
                          name="pending"
                          value={formData.pending}
                          readOnly
                          className={`
                            w-full px-3 py-1.5 rounded-md text-sm
                            ${isDarkMode ? 'bg-gray-700/50' : 'bg-gray-100/70'}
                            backdrop-blur-sm border border-white/10 dark:border-white/5
                            focus:outline-none
                            text-gray-700 dark:text-gray-300
                          `}
                        />
                      </div>
                    </div>
                  </div>

                  {/* 第四列 */}
                  <div className="space-y-3">
                    {/* 备注 */}
                    <div>
                      <label htmlFor="remark" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        备注
                      </label>
                      <textarea
                        id="remark"
                        name="remark"
                        value={formData.remark || ''}
                        onChange={handleChange}
                        rows={3}
                        placeholder="请输入备注信息"
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                          resize-none
                        `}
                      />
                    </div>
                  </div>
                </div>
                
                {/* 提交按钮 */}
                <div className="flex justify-end mt-4">
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className={`
                      px-5 py-2 rounded-lg text-white font-medium text-sm
                      flex items-center justify-center
                      transition-all duration-200
                      ${isSubmitting
                        ? 'bg-blue-400/80 cursor-not-allowed'
                        : `${isDarkMode ? 'bg-blue-600/80 hover:bg-blue-500/80' : 'bg-blue-500 hover:bg-blue-600'} 
                          hover:shadow-md hover:scale-[1.02] active:scale-[0.98]`
                      }
                      backdrop-blur-md border border-white/20
                    `}
                  >
                    {isSubmitting ? (
                      <div className="flex items-center">
                        <svg className="animate-spin h-4 w-4 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        提交中...
                      </div>
                    ) : '创建销售记录'}
                  </button>
                </div>
              </Card>
            </div>
          </form>
        </>
      )}
    </div>
  );
}


