/**
 * 客户选择器组件
 * 作者: 阿瑞
 * 功能: 提供客户搜索和选择功能
 * 版本: 2.0.0
 */

'use client';

import React, { useState, useEffect } from 'react';
import { Customer } from '@/models/team/types/old/customer';
import { MdPerson, MdPhone, MdPersonAddAlt } from 'react-icons/md';
import { useThemeMode } from '@/store/settingStore';
import { ThemeMode } from '@/types/enum';
import { Select, Spin } from 'antd';
import Button from '@/components/ui/Button';
import CustomerModal from '@/app/team/[teamCode]/customers/customer-modal';

interface CustomerSelectorProps {
  teamCode: string;
  selectedCustomer: Customer | null;
  onSelectCustomer: (customer: Customer) => void;
}

/**
 * 客户选择器组件 - 下拉列表版本
 */
const CustomerSelector: React.FC<CustomerSelectorProps> = ({
  teamCode,
  selectedCustomer,
  onSelectCustomer
}) => {
  // 主题模式
  const themeMode = useThemeMode();
  const isDarkMode = themeMode === ThemeMode.Dark;

  // 客户列表状态
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(false);

  // 客户模态框状态
  const [isCustomerModalOpen, setIsCustomerModalOpen] = useState(false);

  /**
   * 加载客户列表
   */
  useEffect(() => {
    const loadCustomers = async () => {
      if (!teamCode) return;
      
      setLoading(true);
      try {
        const response = await fetch(`/api/team/${teamCode}/customers?pageSize=100`);
        
        if (response.ok) {
          const data = await response.json();
          setCustomers(data.customers || []);
        }
      } catch (error) {
        console.error('加载客户列表失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadCustomers();
  }, [teamCode]);

  /**
   * 处理选择客户
   */
  const handleChange = (value: string) => {
    const selectedCust = customers.find(c => c.id.toString() === value);
    if (selectedCust) {
      onSelectCustomer(selectedCust);
    }
  };

  /**
   * 打开新增客户模态框
   */
  const handleOpenCustomerModal = () => {
    setIsCustomerModalOpen(true);
  };

  /**
   * 关闭新增客户模态框
   */
  const handleCloseCustomerModal = () => {
    setIsCustomerModalOpen(false);
  };

  /**
   * 处理新增客户成功
   * 刷新客户列表并选中新增的客户
   */
  const handleCustomerSuccess = async () => {
    // 先关闭模态框
    setIsCustomerModalOpen(false);
    
    // 显示"正在加载"状态
    setLoading(true);
    
    try {
      // 获取最新创建的客户（第一个）并设为选中状态
      const response = await fetch(`/api/team/${teamCode}/customers?sortBy=createdAt&sortOrder=desc&pageSize=1`);

      if (response.ok) {
        const data = await response.json();
        if (data.customers && data.customers.length > 0) {
          const newCustomer = data.customers[0];
          onSelectCustomer(newCustomer);
        }
      }
      
      // 刷新客户列表
      const allCustomersResponse = await fetch(`/api/team/${teamCode}/customers?pageSize=100`);
      
      if (allCustomersResponse.ok) {
        const data = await allCustomersResponse.json();
        setCustomers(data.customers || []);
      }
    } catch (error) {
      console.error('获取新增客户失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex gap-2">
      <div className="flex-grow">
        <Select
          showSearch
          style={{ width: '100%' }}
          placeholder="选择客户..."
          optionFilterProp="children"
          notFoundContent={loading ? <Spin size="small" /> : "未找到客户"}
          filterOption={(input, option) => 
            (option?.label as string).toLowerCase().includes(input.toLowerCase()) ||
            ((option?.data as any).phone || '').includes(input)
          }
          onChange={handleChange}
          loading={loading}
          optionLabelProp="label"
          value={selectedCustomer?.id.toString()}
          options={customers.map(customer => ({
            value: customer.id.toString(),
            label: customer.name,
            data: customer
          }))}
          popupRender={menu => (
            <div style={{ maxHeight: '400px', overflow: 'auto' }}>
              {menu}
            </div>
          )}
          optionRender={(option) => {
            const customer = (option.data as any).data;
            return (
              <div style={{ display: 'flex', padding: '4px 0' }}>
                <div className={`
                  flex items-center justify-center w-7 h-7 rounded-full mr-3 flex-shrink-0
                  ${isDarkMode ? 'bg-blue-600/30' : 'bg-blue-100'}
                  text-blue-600 dark:text-blue-400
                `}>
                  <MdPerson size={16} />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div style={{ fontWeight: 'bold', display: 'flex', alignItems: 'center' }}>
                    {customer.name}
                    {customer.gender && (
                      <span style={{ 
                        marginLeft: '8px', 
                        fontSize: '12px', 
                        padding: '0px 6px', 
                        borderRadius: '10px',
                        background: customer.gender === '男' 
                          ? (isDarkMode ? 'rgba(37, 99, 235, 0.2)' : '#e0e7ff') 
                          : (isDarkMode ? 'rgba(219, 39, 119, 0.2)' : '#fce7f3'),
                        color: customer.gender === '男' 
                          ? (isDarkMode ? '#93c5fd' : '#1d4ed8') 
                          : (isDarkMode ? '#f9a8d4' : '#be185d')
                      }}>
                        {customer.gender}
                      </span>
                    )}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', fontSize: '12px', color: '#888' }}>
                    <MdPhone style={{ marginRight: '4px' }} size={14} />
                    {customer.phone}
                  </div>
                </div>
              </div>
            );
          }}
        />
      </div>
      
      {/* 新增客户按钮 */}
      <Button
        variant="success"
        size="md"
        icon={<MdPersonAddAlt size={16} />}
        onClick={handleOpenCustomerModal}
        className="flex-shrink-0"
      >
        新增
      </Button>

      {/* 客户新增模态框 */}
      <CustomerModal
        isOpen={isCustomerModalOpen}
        onClose={handleCloseCustomerModal}
        customer={null}
        onSuccess={handleCustomerSuccess}
      />
    </div>
  );
};

export default CustomerSelector; 