import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Department } from '../../types/department';
import { 
  ChevronRight,
  ChevronDown,
  Plus,
  Edit,
  Trash2,
  Building2,
  GripVertical
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function DepartmentManagement() {
  const [departments, setDepartments] = useState<Department[]>([]);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [showForm, setShowForm] = useState(false);
  const [editingDepartment, setEditingDepartment] = useState<Department | null>(null);
  const [parentDepartment, setParentDepartment] = useState<Department | null>(null);
  const [formData, setFormData] = useState<Partial<Department>>({
    status: 'active',
    sort: 0,
    level: 1,
  });
  const [draggedItem, setDraggedItem] = useState<{ dept: Department; index: number; parentId?: string } | null>(null);
  const [dragOverItem, setDragOverItem] = useState<{ index: number; parentId?: string } | null>(null);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deletingDepartment, setDeletingDepartment] = useState<Department | null>(null);

  useEffect(() => {
    loadDepartments();
  }, []);

  const loadDepartments = () => {
    const data = localStorage.getItem('smart_agriculture_departments');
    if (data) {
      setDepartments(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockDepartments: Department[] = [
        {
          id: 'dept-1',
          name: '技术部',
          code: 'TECH',
          level: 1,
          manager: '王技术',
          phone: '13800138001',
          email: 'tech@example.com',
          description: '负责技术研发和系统维护',
          sort: 1,
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          children: [
            {
              id: 'dept-1-1',
              parentId: 'dept-1',
              name: '研发组',
              code: 'TECH-RD',
              level: 2,
              manager: '李研发',
              phone: '13800138011',
              description: '负责系统研发',
              sort: 1,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
            {
              id: 'dept-1-2',
              parentId: 'dept-1',
              name: '运维组',
              code: 'TECH-OPS',
              level: 2,
              manager: '张运维',
              phone: '13800138012',
              description: '负责系统运维',
              sort: 2,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
          ],
        },
        {
          id: 'dept-2',
          name: '管理部',
          code: 'ADMIN',
          level: 1,
          manager: '赵管理',
          phone: '13800138002',
          email: 'admin@example.com',
          description: '负责行政管理',
          sort: 2,
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          children: [
            {
              id: 'dept-2-1',
              parentId: 'dept-2',
              name: '人事组',
              code: 'ADMIN-HR',
              level: 2,
              manager: '孙人事',
              phone: '13800138021',
              description: '负责人力资源管理',
              sort: 1,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
            {
              id: 'dept-2-2',
              parentId: 'dept-2',
              name: '财务组',
              code: 'ADMIN-FIN',
              level: 2,
              manager: '周财务',
              phone: '13800138022',
              description: '负责财务管理',
              sort: 2,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
          ],
        },
        {
          id: 'dept-3',
          name: '作业部',
          code: 'OPS',
          level: 1,
          manager: '吴作业',
          phone: '13800138003',
          email: 'ops@example.com',
          description: '负责农机作业管理',
          sort: 3,
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          children: [
            {
              id: 'dept-3-1',
              parentId: 'dept-3',
              name: '第一作业组',
              code: 'OPS-T1',
              level: 2,
              manager: '郑组长',
              phone: '13800138031',
              description: '负责区域A作业',
              sort: 1,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
            {
              id: 'dept-3-2',
              parentId: 'dept-3',
              name: '第二作业组',
              code: 'OPS-T2',
              level: 2,
              manager: '钱组长',
              phone: '13800138032',
              description: '负责区域B作业',
              sort: 2,
              status: 'active',
              createdAt: '2024-01-01T00:00:00',
              updatedAt: '2024-01-01T00:00:00',
            },
          ],
        },
      ];
      localStorage.setItem('smart_agriculture_departments', JSON.stringify(mockDepartments));
      setDepartments(mockDepartments);
      // 默认展开所有一级部门
      setExpandedIds(new Set(mockDepartments.map(d => d.id)));
    }
  };

  // 统计部门数量
  const countDepartments = (depts: Department[]): { level1: number; level2: number; total: number } => {
    let level1 = 0;
    let level2 = 0;

    depts.forEach(dept => {
      if (!dept.parentId) {
        level1++;
        if (dept.children) {
          level2 += dept.children.length;
        }
      }
    });

    return { level1, level2, total: level1 + level2 };
  };

  const stats = countDepartments(departments);

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedIds);
    if (newExpanded.has(id)) {
      newExpanded.delete(id);
    } else {
      newExpanded.add(id);
    }
    setExpandedIds(newExpanded);
  };

  const handleAdd = (parent?: Department) => {
    setEditingDepartment(null);
    setParentDepartment(parent || null);
    
    const level = parent ? (parent.level || 1) + 1 : 1;
    
    setFormData({
      parentId: parent?.id,
      level,
      status: 'active',
      sort: 0,
    });
    setShowForm(true);
  };

  const handleEdit = (dept: Department) => {
    setEditingDepartment(dept);
    setParentDepartment(null);
    setFormData({
      ...dept,
      children: undefined,
    });
    setShowForm(true);
  };

  const handleSave = () => {
    if (!formData.name || !formData.code) {
      toast.error('请填写必填项');
      return;
    }

    const now = new Date().toISOString();

    if (editingDepartment) {
      // 更新部门
      const updateInTree = (items: Department[]): Department[] => {
        return items.map(item => {
          if (item.id === editingDepartment.id) {
            return {
              ...item,
              ...formData,
              updatedAt: now,
              children: item.children,
            } as Department;
          }
          if (item.children) {
            return {
              ...item,
              children: updateInTree(item.children),
            };
          }
          return item;
        });
      };

      const updated = updateInTree(departments);
      setDepartments(updated);
      localStorage.setItem('smart_agriculture_departments', JSON.stringify(updated));
      toast.success('部门更新成功');
    } else {
      // 新增部门
      const newDept: Department = {
        id: `dept-${Date.now()}`,
        ...formData as Department,
        createdAt: now,
        updatedAt: now,
      };

      if (parentDepartment) {
        // 添加到父部门下
        const addToParent = (items: Department[]): Department[] => {
          return items.map(item => {
            if (item.id === parentDepartment.id) {
              return {
                ...item,
                children: [...(item.children || []), newDept],
              };
            }
            if (item.children) {
              return {
                ...item,
                children: addToParent(item.children),
              };
            }
            return item;
          });
        };

        const updated = addToParent(departments);
        setDepartments(updated);
        localStorage.setItem('smart_agriculture_departments', JSON.stringify(updated));
        setExpandedIds(prev => new Set([...prev, parentDepartment.id]));
      } else {
        // 添加为一级部门
        const updated = [...departments, newDept];
        setDepartments(updated);
        localStorage.setItem('smart_agriculture_departments', JSON.stringify(updated));
      }

      toast.success('部门添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (dept: Department) => {
    if (dept.children && dept.children.length > 0) {
      toast.error('请先删除该部门下的子部门');
      return;
    }

    setDeletingDepartment(dept);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (!deletingDepartment) return;

    const deleteFromTree = (items: Department[]): Department[] => {
      return items
        .filter(item => item.id !== deletingDepartment.id)
        .map(item => {
          if (item.children) {
            return {
              ...item,
              children: deleteFromTree(item.children),
            };
          }
          return item;
        });
    };

    const updated = deleteFromTree(departments);
    setDepartments(updated);
    localStorage.setItem('smart_agriculture_departments', JSON.stringify(updated));
    toast.success('部门删除成功');
    
    setShowDeleteDialog(false);
    setDeletingDepartment(null);
  };

  // 保存部门到localStorage
  const saveDepartments = (updatedDepts: Department[]) => {
    setDepartments(updatedDepts);
    localStorage.setItem('smart_agriculture_departments', JSON.stringify(updatedDepts));
  };

  // 拖动开始
  const handleDragStart = (e: React.DragEvent, dept: Department, index: number, parentId?: string) => {
    setDraggedItem({ dept, index, parentId });
    e.dataTransfer.effectAllowed = 'move';
    if (e.currentTarget instanceof HTMLElement) {
      e.currentTarget.style.opacity = '0.5';
    }
  };

  // 拖动结束
  const handleDragEnd = (e: React.DragEvent) => {
    if (e.currentTarget instanceof HTMLElement) {
      e.currentTarget.style.opacity = '1';
    }
    setDraggedItem(null);
    setDragOverItem(null);
  };

  // 拖动经过
  const handleDragOver = (e: React.DragEvent, index: number, parentId?: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    
    if (draggedItem && draggedItem.parentId === parentId) {
      setDragOverItem({ index, parentId });
    }
  };

  // 拖动离开
  const handleDragLeave = () => {
    setDragOverItem(null);
  };

  // 放置
  const handleDrop = (e: React.DragEvent, hoverIndex: number, parentId?: string) => {
    e.preventDefault();
    
    if (!draggedItem) return;
    
    if (draggedItem.parentId !== parentId) {
      toast.error('不能跨级别拖动部门');
      setDragOverItem(null);
      return;
    }

    const dragIndex = draggedItem.index;
    if (dragIndex === hoverIndex) {
      setDragOverItem(null);
      return;
    }

    let updated: Department[];

    if (!parentId) {
      // 一级部门
      const newDepts = [...departments];
      const [removed] = newDepts.splice(dragIndex, 1);
      newDepts.splice(hoverIndex, 0, removed);
      
      updated = newDepts.map((item, index) => ({
        ...item,
        sort: index + 1,
      }));
    } else {
      // 二级部门
      const updateInTree = (items: Department[]): Department[] => {
        return items.map(item => {
          if (item.id === parentId && item.children) {
            const newChildren = [...item.children];
            const [removed] = newChildren.splice(dragIndex, 1);
            newChildren.splice(hoverIndex, 0, removed);
            
            return {
              ...item,
              children: newChildren.map((child, index) => ({
                ...child,
                sort: index + 1,
              })),
            };
          }
          if (item.children) {
            return {
              ...item,
              children: updateInTree(item.children),
            };
          }
          return item;
        });
      };

      updated = updateInTree(departments);
    }

    saveDepartments(updated);
    toast.success('部门顺序已更新');
    setDragOverItem(null);
  };

  const getStatusBadge = (status: string) => {
    return status === 'active' ? (
      <Badge className="bg-green-100 dark:bg-green-100 text-green-700 dark:text-green-700">启用</Badge>
    ) : (
      <Badge className="bg-gray-100 dark:bg-gray-100 text-gray-700 dark:text-gray-700">停用</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) => handleDragStart(e, dept, index, parentId)}
            onDragEnd={handleDragEnd}
            onDragOver={(e) => handleDragOver(e, index, parentId)}
            onDragLeave={handleDragLeave}
            onDrop={(e) => handleDrop(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={() => toggleExpand(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">
              {level < 1 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleAdd(dept)}
                  title="添加子部门"
                >
                  <Plus className="w-4 h-4 text-green-600 dark:text-green-400" />
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(dept)}
                title="编辑"
              >
                <Edit className="w-4 h-4 text-blue-600 dark:text-blue-400" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDelete(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>
      );
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-400">部门管理</h2>
          <p className="text-muted-foreground">树形结构管理企业部门信息，支持拖动排序</p>
        </div>
        <Button onClick={() => handleAdd()} className="bg-green-600 hover:bg-green-700 dark:bg-green-600 dark:hover:bg-green-700">
          <Plus className="w-4 h-4 mr-2" />
          添加一级部门
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-3 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">一级部门</div>
          <div className="mt-2 text-blue-600 dark:text-blue-400">{stats.level1}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">二级部门</div>
          <div className="mt-2 text-green-600 dark:text-green-400">{stats.level2}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">部门总数</div>
          <div className="mt-2 text-orange-600 dark:text-orange-400">{stats.total}</div>
        </Card>
      </div>

      {/* 部门树 */}
      <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={() => setExpandedIds(new Set(departments.map(d => d.id)))}
            >
              展开全部
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setExpandedIds(new Set())}
            >
              收起全部
            </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>

      {/* 添加/编辑表单 */}
      <Dialog open={showForm} onOpenChange={setShowForm}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editingDepartment ? '编辑部门' : parentDepartment ? `添加子部门（父级：${parentDepartment.name}）` : '添加一级部门'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingDepartment ? '编辑部门信息' : '添加新部门'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="name">部门名称 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="请输入部门名称"
                />
              </div>
              <div>
                <Label htmlFor="code">部门编码 *</Label>
                <Input
                  id="code"
                  value={formData.code || ''}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="请输入部门编码，如：TECH"
                />
              </div>
              <div>
                <Label htmlFor="manager">负责人</Label>
                <Input
                  id="manager"
                  value={formData.manager || ''}
                  onChange={(e) => setFormData({ ...formData, manager: e.target.value })}
                  placeholder="请输入负责人姓名"
                />
              </div>
              <div>
                <Label htmlFor="phone">联系电话</Label>
                <Input
                  id="phone"
                  value={formData.phone || ''}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  placeholder="请输入联系电话"
                />
              </div>
              <div>
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email || ''}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  placeholder="请输入邮箱"
                />
              </div>
              <div>
                <Label htmlFor="sort">排序号 *</Label>
                <Input
                  id="sort"
                  type="number"
                  value={formData.sort || 0}
                  onChange={(e) => setFormData({ ...formData, sort: parseInt(e.target.value) || 0 })}
                  placeholder="数字越小越靠前"
                />
              </div>
              <div>
                <Label htmlFor="status">状态 *</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value: 'active' | 'inactive') => setFormData({ ...formData, status: value })}
                >
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">启用</SelectItem>
                    <SelectItem value="inactive">停用</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label htmlFor="description">部门描述</Label>
              <Input
                id="description"
                value={formData.description || ''}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="请输入部门描述"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowForm(false)}>
              取消
            </Button>
            <Button onClick={handleSave} className="bg-green-600 hover:bg-green-700 dark:bg-green-600 dark:hover:bg-green-700">
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除部门"{deletingDepartment?.name}"吗？此操作不可恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button 
              variant="outline" 
              onClick={() => {
                setShowDeleteDialog(false);
                setDeletingDepartment(null);
              }}
            >
              取消
            </Button>
            <Button 
              variant="destructive" 
              onClick={confirmDelete}
            >
              确认删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 功能说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
        <h4 className="text-blue-900 dark:text-blue-400 mb-2">部门管理说明</h4>
        <ul className="space-y-1 text-sm text-blue-800 dark:text-blue-300">
          <li>• <strong>树形结构：</strong>支持二级部门管理（一级部门 → 二级部门）</li>
          <li>• <strong>拖动排序：</strong>按住部门左侧的 ⋮⋮ 图标拖动，可调整同级部门的顺序</li>
          <li>• <strong>部门编码：</strong>建议使用英文大写字母，如TECH、ADMIN等</li>
          <li>• <strong>员工关联：</strong>在员工管理中新增员工时，可选择此处维护的部门</li>
          <li>• <strong>删除限制：</strong>删除部门前请先删除其所有子部门</li>
          <li>• 部门状态为"停用"时，该部门仍可查看但不可用于新建员工</li>
        </ul>
      </Card>
    </div>
  );
}
