/**
 * filekorolheader: 部门树组件 - 部门树形结构展示界面
 * 功能：部门树形展示、展开收起、拖拽排序、操作按钮
 * 路径：/central-config/user/department/components/DepartmentTree
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn/ui组件，TypeScript类型安全
 */

import { Department } from '../types';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  ChevronRight,
  ChevronDown,
  Plus,
  Edit,
  Trash2,
  Building2,
  GripVertical
} from 'lucide-react';

interface DepartmentTreeProps {
  departments: Department[];
  expandedIds: Set<string>;
  loading: boolean;
  draggedItem: {
    dept: Department;
    index: number;
    parentId?: string;
  } | null;
  dragOverItem: {
    index: number;
    parentId?: string;
  } | null;
  onToggleExpand: (id: string) => void;
  onExpandAll: () => void;
  onCollapseAll: () => void;
  onAdd: (parent?: Department) => void;
  onEdit: (dept: Department) => void;
  onDelete: (dept: Department) => void;
  onDragStart: (dept: Department, index: number, parentId?: string) => void;
  onDragEnd: () => void;
  onDragOver: (e: React.DragEvent, index: number, parentId?: string) => void;
  onDragLeave: () => void;
  onDrop: (e: React.DragEvent, hoverIndex: number, parentId?: string) => void;
}

export function DepartmentTree({
  departments,
  expandedIds,
  loading,
  draggedItem,
  dragOverItem,
  onToggleExpand,
  onExpandAll,
  onCollapseAll,
  onAdd,
  onEdit,
  onDelete,
  onDragStart,
  onDragEnd,
  onDragOver,
  onDragLeave,
  onDrop
}: DepartmentTreeProps) {
  const getStatusBadge = (status: string) => {
    return status === 'active' ? (
      <Badge className="bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">启用</Badge>
    ) : (
      <Badge className="bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300">停用</Badge>
    );
  };

  // 渲染部门树
  const renderDepartmentTree = (items: Department[], level: number = 0, parentId?: string) => {
    return items.map((dept, index) => {
      const isExpanded = expandedIds.has(dept.id);
      const hasChildren = dept.children && dept.children.length > 0;
      const indent = level * 24;

      const isDragOver = dragOverItem?.index === index && dragOverItem?.parentId === parentId;
      const isDragging = draggedItem?.dept.id === dept.id;

      return (
        <div key={dept.id}>
          <div
            draggable
            onDragStart={(e) => onDragStart(dept, index, parentId)}
            onDragEnd={onDragEnd}
            onDragOver={(e) => onDragOver(e, index, parentId)}
            onDragLeave={onDragLeave}
            onDrop={(e) => onDrop(e, index, parentId)}
            className={`flex items-center justify-between p-3 border rounded-lg mb-2 transition-all ${
              isDragging
                ? 'opacity-50 bg-muted'
                : isDragOver
                  ? 'bg-green-50 dark:bg-green-950/30 border-green-300 dark:border-green-700'
                  : 'hover:bg-muted/50'
            }`}
            style={{ marginLeft: `${indent}px`, cursor: 'move' }}
          >
            <div className="flex items-center gap-3 flex-1">
              {/* 拖动手柄 */}
              <div className="cursor-grab active:cursor-grabbing" title="拖动调整顺序">
                <GripVertical className="w-4 h-4 text-muted-foreground hover:text-green-600 dark:hover:text-green-400" />
              </div>

              {/* 展开/收起图标 */}
              <div className="w-5 flex items-center justify-center">
                {hasChildren ? (
                  <button
                    onClick={() => onToggleExpand(dept.id)}
                    className="hover:bg-muted rounded p-0.5"
                  >
                    {isExpanded ? (
                      <ChevronDown className="w-4 h-4 text-muted-foreground" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-muted-foreground" />
                    )}
                  </button>
                ) : (
                  <div className="w-4" />
                )}
              </div>

              {/* 部门图标 */}
              <Building2 className="w-5 h-5 text-blue-600 dark:text-blue-400" />

              {/* 部门信息 */}
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span>{dept.name}</span>
                  <span className="text-xs text-muted-foreground">({dept.code})</span>
                </div>
                {dept.manager && (
                  <div className="text-xs text-muted-foreground mt-0.5">
                    负责人：{dept.manager}
                    {dept.phone && ` · ${dept.phone}`}
                  </div>
                )}
              </div>

              {/* 状态标签 */}
              <div className="flex items-center gap-2">
                {getStatusBadge(dept.status)}
                <span className="text-xs text-muted-foreground">排序: {dept.sort}</span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex items-center gap-1 ml-4">
              {/* 所有节点都可以添加子部门 */}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => onAdd(dept)}
                title="添加子部门"
              >
                <Plus className="w-4 h-4 text-green-600 dark:text-green-400" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => onEdit(dept)}
                title="编辑"
              >
                <Edit className="w-4 h-4 text-blue-600 dark:text-blue-400" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => onDelete(dept)}
                title="删除"
              >
                <Trash2 className="w-4 h-4 text-red-600 dark:text-red-400" />
              </Button>
            </div>
          </div>

          {/* 递归渲染子部门 */}
          {hasChildren && isExpanded && (
            <div className="mt-2">
              {renderDepartmentTree(dept.children!, level + 1, dept.id)}
            </div>
          )}
        </div>
      );
    });
  };

  if (loading) {
    return (
      <Card className="p-6">
        <div className="flex items-center justify-center h-96">
          <div className="text-muted-foreground">加载中...</div>
        </div>
      </Card>
    );
  }

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-4">
        <h3>部门结构</h3>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={onExpandAll}
          >
            展开全部
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={onCollapseAll}
          >
            收起全部
          </Button>
        </div>
      </div>

      <div className="space-y-2">
        {departments.length > 0 ? (
          renderDepartmentTree(departments)
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            暂无部门数据，点击上方按钮添加一级部门
          </div>
        )}
      </div>
    </Card>
  );
}