import React, { useState, useEffect } from 'react';
import { Search, ChevronRight, ChevronDown, Building2 } from 'lucide-react';
import { deptApi } from '../../api/dept';
import { WorkstationNode } from '../../types';
import { handleTree } from '../../utils/tree';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';

interface DeptTreeProps {
  onNodeClick: (node: WorkstationNode) => void;
}

export default function DeptTree({ onNodeClick }: DeptTreeProps) {
  const { t } = useTranslation();
  const [deptName, setDeptName] = useState('');
  const [deptList, setDeptList] = useState<WorkstationNode[]>([]);
  const [expandedIds, setExpandedIds] = useState<number[]>([]);
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);

  // 获取部门树
  const getTree = async (searchName?: string) => {
    setLoading(true);
    try {
      // 如果有搜索关键词，调用带参数的接口；否则调用精简列表接口
      let deptList;
      if (searchName && searchName.trim()) {
        // 调用带搜索参数的接口
        deptList = await deptApi.getDeptPage({ name: searchName.trim() });
      } else {
        // 调用精简列表接口
        deptList = await deptApi.getSimpleDeptList();
      }
      
      // 将部门数据转换为 WorkstationNode 格式
      const workstationList = deptList.map(dept => ({
        id: dept.id!,
        workstationName: dept.name,
        parentId: dept.parentId,
      }));
      
      // 转换为树形结构
      const treeData = handleTree(workstationList, 'id', 'parentId', 'children') as WorkstationNode[];
      setDeptList(treeData);
      
      // 默认展开第一层
      if (treeData.length > 0) {
        setExpandedIds([treeData[0].id]);
      }
    } catch (error: any) {
      console.error('获取部门树失败:', error);
      toast.error(error.message || '获取部门树失败');
      setDeptList([]);
    } finally {
      setLoading(false);
    }
  };

  // 递归渲染树节点
  const renderTreeNode = (nodes: WorkstationNode[], level: number = 0): React.ReactNode[] => {
    return nodes.map(node => {
        const isExpanded = expandedIds.includes(node.id);
        const isSelected = selectedId === node.id;
        const hasChildren = node.children && node.children.length > 0;

        return (
          <div key={node.id}>
            <div
              onClick={() => {
                if (hasChildren) {
                  setExpandedIds(prev =>
                    prev.includes(node.id) ? prev.filter(id => id !== node.id) : [...prev, node.id]
                  );
                }
                setSelectedId(node.id);
                onNodeClick(node);
              }}
              className={`flex items-center gap-2 px-3 py-2.5 rounded-lg cursor-pointer transition-all group ${
                isSelected
                  ? 'bg-blue-500 text-white shadow-md'
                  : 'hover:bg-blue-50 text-gray-700'
              }`}
              style={{ paddingLeft: `${level * 20 + 12}px` }}
            >
              {hasChildren ? (
                isExpanded ? (
                  <ChevronDown className={`w-4 h-4 flex-shrink-0 ${
                    isSelected ? 'text-white' : 'text-gray-600'
                  }`} />
                ) : (
                  <ChevronRight className={`w-4 h-4 flex-shrink-0 ${
                    isSelected ? 'text-white' : 'text-gray-600'
                  }`} />
                )
              ) : (
                <span className="w-4"></span>
              )}
              
              <Building2 className={`w-4 h-4 flex-shrink-0 ${
                isSelected ? 'text-white' : 'text-blue-500'
              }`} />
              
              <span className="text-sm truncate">{node.workstationName}</span>
            </div>
            
            {hasChildren && isExpanded && (
              <div className="mt-1">
                {renderTreeNode(node.children!, level + 1)}
              </div>
            )}
          </div>
        );
      });
  };

  // 初始化加载
  useEffect(() => {
    getTree();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 处理搜索输入变化（防抖）
  useEffect(() => {
    const timer = setTimeout(() => {
      if (deptName.trim()) {
        getTree(deptName);
      } else {
        getTree();
      }
    }, 300);

    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deptName]);

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 py-4 border-b border-gray-200/50 flex-shrink-0">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            value={deptName}
            onChange={(e) => setDeptName(e.target.value)}
            placeholder={t('form.departmentNamePlaceholder')}
            className="w-full h-9 pl-9 pr-3 bg-gray-50 border border-gray-200 rounded-lg outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all text-sm"
          />
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto p-3">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
          </div>
        ) : (
          <div className="space-y-1">
            {deptList.length === 0 ? (
              <div className="text-center py-8 text-gray-400 text-sm">{t('common.noData')}</div>
            ) : (
              renderTreeNode(deptList, 0)
            )}
          </div>
        )}
      </div>
    </div>
  );
}

