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

'use client';

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { MdSearch, MdRefresh, MdPersonAdd, MdPerson, MdArrowDropDown, MdClose } from 'react-icons/md';
import { useTheme } from '@/hooks';

// 地址接口类型
interface CustomerAddress {
  province?: string;
  city?: string;
  district?: string;
  detail?: string;
  postalCode?: string;
}

// 客户接口类型
export interface Customer {
  id: number;
  name: string;
  phone?: string;
  gender?: string;
  wechat?: string;
  address?: CustomerAddress;
  birthday?: string;
  followDate?: string;
  balance?: number;
  createdAt?: string;
  updatedAt?: string;
}

interface CustomerSelectorProps {
  selectedCustomer: Customer | null;
  onSelectCustomer: (customer: Customer) => void;
  teamCode: string;
  onCreateCustomer?: () => void; // 新增客户回调
}

/**
 * 客户选择器组件
 * 用于搜索和选择客户
 */
const CustomerSelector: React.FC<CustomerSelectorProps> = ({
  selectedCustomer,
  onSelectCustomer,
  teamCode,
  onCreateCustomer
}) => {
  const { isDarkMode } = useTheme();
  const [searchQuery, setSearchQuery] = useState('');
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [debouncedQuery, setDebouncedQuery] = useState('');
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  
  // 节流查询，300ms后执行
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(searchQuery);
    }, 300);
    
    return () => clearTimeout(timer);
  }, [searchQuery]);
  
  // 获取客户列表
  const fetchCustomers = useCallback(async (keyword: string = '') => {
    if (!teamCode) return;
    
    setIsLoading(true);
    setErrorMessage(null);
    
    try {
      // 构建API URL
      const url = `/api/team/${teamCode}/customers?pageSize=20${keyword ? `&keyword=${encodeURIComponent(keyword)}` : ''}`;
      
      const response = await fetch(url);
      const data = await response.json();
      
      if (data.success) {
        setCustomers(data.customers || []);
      } else {
        setErrorMessage(data.error || '获取客户列表失败');
        setCustomers([]);
      }
    } catch {
      setErrorMessage('网络请求失败，请稍后重试');
      setCustomers([]);
    } finally {
      setIsLoading(false);
    }
  }, [teamCode]);
  
  // 初始加载和查询变化时获取数据
  useEffect(() => {
    fetchCustomers(debouncedQuery);
    if (debouncedQuery.length > 0 && !isDropdownOpen) {
      setIsDropdownOpen(true);
    }
  }, [fetchCustomers, debouncedQuery, isDropdownOpen]);
  
  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  // 手动刷新
  const handleRefresh = () => {
    fetchCustomers(debouncedQuery);
    if (!isDropdownOpen) {
      setIsDropdownOpen(true);
    }
  };
  
  // 处理搜索输入变化
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    if (e.target.value.length > 0 && !isDropdownOpen) {
      setIsDropdownOpen(true);
    }
  };
  
  // 创建新客户
  const handleCreateCustomer = () => {
    if (onCreateCustomer) {
      onCreateCustomer();
      setIsDropdownOpen(false);
    }
  };
  
  // 选择客户
  const handleSelectCustomer = (customer: Customer) => {
    onSelectCustomer(customer);
    setIsDropdownOpen(false);
    setSearchQuery('');
  };
  
  // 清除选择的客户
  const handleClearSelection = (e?: React.MouseEvent) => {
    e?.stopPropagation();
    // 使用as null来解决类型问题，因为接口定义是Customer | null
    onSelectCustomer(null as unknown as Customer);
    setSearchQuery('');
    inputRef.current?.focus();
  };
  
  // 处理下拉框切换
  const toggleDropdown = () => {
    setIsDropdownOpen(!isDropdownOpen);
    if (!isDropdownOpen) {
      fetchCustomers(searchQuery);
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  };
  
  // 渲染客户列表项
  const renderCustomerList = () => {
    if (isLoading) {
      return (
        <div className="p-4 text-center text-gray-500 dark:text-gray-400">
          加载中...
        </div>
      );
    }
    
    if (customers.length > 0) {
      return (
        <div className="max-h-64 overflow-y-auto">
          {customers.map(customer => (
            <div 
              key={customer.id}
              onClick={() => handleSelectCustomer(customer)}
              className={`
                p-3 cursor-pointer
                ${isDarkMode ? 'hover:bg-slate-700/50' : 'hover:bg-gray-50'}
                border-b border-gray-100 dark:border-gray-800
                transition-colors duration-150
              `}
            >
              <div className="font-medium flex items-center">
                {customer.name}
                {customer.gender && (
                  <span className={`ml-2 text-xs px-1.5 py-0.5 rounded-full ${customer.gender === '女' ? 
                    (isDarkMode ? 'bg-pink-900/30 text-pink-300' : 'bg-pink-100 text-pink-700') : 
                    (isDarkMode ? 'bg-blue-900/30 text-blue-300' : 'bg-blue-100 text-blue-700')}`
                  }>
                    {customer.gender}
                  </span>
                )}
              </div>
              <div className="flex flex-wrap gap-2 mt-1">
                {customer.phone && <div className="text-xs text-gray-500 dark:text-gray-400">{customer.phone}</div>}
                {customer.wechat && <div className="text-xs text-gray-500 dark:text-gray-400">微信：{customer.wechat}</div>}
              </div>
            </div>
          ))}
        </div>
      );
    }
    
    if (customers.length === 0 && debouncedQuery) {
      return (
        <div className="p-4 text-center text-gray-500 dark:text-gray-400">
          没有找到匹配的客户
          {onCreateCustomer && (
            <button
              type="button"
              onClick={handleCreateCustomer}
              className="block mx-auto mt-2 text-blue-500 dark:text-blue-400 hover:underline text-sm"
            >
              创建新客户
            </button>
          )}
        </div>
      );
    }
    
    if (customers.length === 0) {
      return (
        <div className="flex justify-center items-center flex-col py-6">
          <div className={`w-16 h-16 rounded-full flex items-center justify-center 
            ${isDarkMode ? 'bg-gray-800/50' : 'bg-gray-100'} mb-3`}>
            <MdPerson className={`w-10 h-10 ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`} />
          </div>
          <div className={`text-center ${isDarkMode ? 'text-gray-300' : 'text-gray-600'} text-sm font-medium`}>
            请选择一位客户 或
          </div>
          <button
            type="button"
            onClick={handleCreateCustomer}
            className={`
              mt-2 px-3 py-1.5 rounded-lg flex items-center justify-center text-sm
              ${isDarkMode ? 'bg-blue-600 hover:bg-blue-500' : 'bg-blue-500 hover:bg-blue-600'}
              text-white transition-colors duration-200
            `}
          >
            <MdPersonAdd className="mr-1" size={16} />
            新增客户
          </button>
        </div>
      );
    }
    
    return null;
  };
  
  return (
    <div className="relative" ref={dropdownRef}>
      {/* 搜索输入框 */}
      <div className="relative">
        {selectedCustomer ? (
          <div 
            className={`
              w-full px-3 py-2 rounded-lg flex items-center justify-between
              ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
              backdrop-blur-sm border border-white/20 dark:border-white/10 cursor-pointer
            `}
            onClick={toggleDropdown}
          >
            <div className="flex items-center">
              <div className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
                ${isDarkMode ? 'bg-blue-900/30' : 'bg-blue-100'} mr-2`}>
                <MdPerson className={`w-5 h-5 ${isDarkMode ? 'text-blue-300' : 'text-blue-600'}`} />
              </div>
              <div>
                <div className="font-medium text-gray-800 dark:text-gray-200 flex items-center">
                  {selectedCustomer.name}
                  {selectedCustomer.gender && (
                    <span className={`ml-2 text-xs px-1.5 py-0.5 rounded-full ${selectedCustomer.gender === '女' ? 
                      (isDarkMode ? 'bg-pink-900/30 text-pink-300' : 'bg-pink-100 text-pink-700') : 
                      (isDarkMode ? 'bg-blue-900/30 text-blue-300' : 'bg-blue-100 text-blue-700')}`
                    }>
                      {selectedCustomer.gender}
                    </span>
                  )}
                </div>
                {selectedCustomer.phone && 
                  <div className="text-xs text-gray-500 dark:text-gray-400">{selectedCustomer.phone}</div>
                }
              </div>
            </div>
            <div className="flex items-center">
              <button
                type="button"
                onClick={handleClearSelection}
                className="p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 mr-1"
                title="清除选择"
              >
                <MdClose size={16} className="text-gray-500 dark:text-gray-400" />
              </button>
              <MdArrowDropDown 
                className={`text-gray-500 dark:text-gray-400 transform transition-transform ${isDropdownOpen ? 'rotate-180' : ''}`} 
                size={20} 
              />
            </div>
          </div>
        ) : (
          <div className="flex">
            <div className="relative flex-1">
              <input
                ref={inputRef}
                type="text"
                placeholder="搜索客户(姓名/手机/微信)..."
                value={searchQuery}
                onChange={handleSearchChange}
                onFocus={() => setIsDropdownOpen(true)}
                className={`
                  w-full px-3 py-2.5 pl-10 pr-10 rounded-lg
                  ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                  backdrop-blur-sm border border-white/20 dark:border-white/10
                  focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                  text-gray-800 dark:text-white
                `}
              />
              <MdSearch className="absolute left-3 top-3 text-gray-500 dark:text-gray-400" size={20} />
              <div className="absolute right-0 top-0 h-full flex items-center pr-1">
                <button 
                  type="button"
                  onClick={handleRefresh}
                  className={`p-1.5 ${isLoading ? 'animate-spin' : ''} text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400`}
                  title="刷新客户列表"
                >
                  <MdRefresh size={20} />
                </button>
                <button
                  type="button"
                  onClick={toggleDropdown}
                  className="p-1.5 text-gray-500 dark:text-gray-400"
                >
                  <MdArrowDropDown 
                    className={`transform transition-transform ${isDropdownOpen ? 'rotate-180' : ''}`} 
                    size={20} 
                  />
                </button>
              </div>
            </div>
            
            {onCreateCustomer && (
              <button
                type="button"
                onClick={handleCreateCustomer}
                className={`
                  ml-2 px-2 rounded-lg flex items-center
                  ${isDarkMode ? 'bg-blue-600/70 hover:bg-blue-500/70' : 'bg-blue-100 hover:bg-blue-200'}
                  ${isDarkMode ? 'text-white' : 'text-blue-700'}
                  transition-colors duration-200
                `}
                title="新建客户"
              >
                <MdPersonAdd size={20} />
              </button>
            )}
          </div>
        )}
      </div>
      
      {/* 错误信息 */}
      {errorMessage && (
        <div className={`mt-2 p-3 text-sm rounded-lg ${isDarkMode ? 'bg-red-900/20 text-red-300' : 'bg-red-50 text-red-700'}`}>
          {errorMessage}
        </div>
      )}
      
      {/* 下拉列表 */}
      {isDropdownOpen && (
        <div className={`
          absolute z-10 mt-1 w-full overflow-hidden rounded-lg
          ${isDarkMode ? 'bg-gray-900 border border-gray-800' : 'bg-white border border-gray-200'} 
          shadow-lg
        `}>
          {renderCustomerList()}
        </div>
      )}
    </div>
  );
};

export default CustomerSelector;