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 { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Switch } from '../ui/switch';
import { CategoryDictionary as CategoryType } from '../../types/system-params';
import { Search, Plus, Edit, Trash2, FolderTree, ChevronRight, ChevronDown, Folder, File } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function CategoryDictionary() {
  const [categories, setCategories] = useState<CategoryType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [showDialog, setShowDialog] = useState(false);
  const [editingCategory, setEditingCategory] = useState<CategoryType | null>(null);
  const [parentCategory, setParentCategory] = useState<CategoryType | null>(null);

  const [formData, setFormData] = useState({
    code: '',
    name: '',
    type: 'industry' as string,
    description: '',
    sortOrder: 0,
    isActive: true,
  });

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

  const loadCategories = () => {
    const data = localStorage.getItem('smart_agriculture_category_dictionary');
    if (data) {
      setCategories(JSON.parse(data));
    } else {
      const mockData: CategoryType[] = [
        {
          id: 'cat-1',
          code: 'IND001',
          name: '种植业',
          type: 'industry',
          level: 1,
          sortOrder: 1,
          description: '农作物种植相关行业',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-2',
          code: 'IND001-01',
          name: '粮食作物',
          type: 'industry',
          parentId: 'cat-1',
          level: 2,
          sortOrder: 1,
          description: '小麦、水稻、玉米等粮食作物',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-3',
          code: 'IND001-02',
          name: '经济作物',
          type: 'industry',
          parentId: 'cat-1',
          level: 2,
          sortOrder: 2,
          description: '棉花、油料、糖料等经济作物',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-4',
          code: 'IND002',
          name: '畜牧业',
          type: 'industry',
          level: 1,
          sortOrder: 2,
          description: '牲畜饲养相关行业',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-5',
          code: 'EQP001',
          name: '动力机械',
          type: 'equipment',
          level: 1,
          sortOrder: 1,
          description: '拖拉机等动力设备',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-6',
          code: 'EQP001-01',
          name: '轮式拖拉机',
          type: 'equipment',
          parentId: 'cat-5',
          level: 2,
          sortOrder: 1,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-7',
          code: 'EQP001-02',
          name: '履带式拖拉机',
          type: 'equipment',
          parentId: 'cat-5',
          level: 2,
          sortOrder: 2,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'cat-8',
          code: 'EQP002',
          name: '收获机械',
          type: 'equipment',
          level: 1,
          sortOrder: 2,
          description: '收割机、采摘机等',
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_category_dictionary', JSON.stringify(mockData));
      setCategories(mockData);
    }
  };

  const saveCategories = (newCategories: CategoryType[]) => {
    localStorage.setItem('smart_agriculture_category_dictionary', JSON.stringify(newCategories));
    setCategories(newCategories);
  };

  const buildTree = (items: CategoryType[]): CategoryType[] => {
    const map = new Map<string, CategoryType>();
    const roots: CategoryType[] = [];

    // 创建映射
    items.forEach(item => {
      map.set(item.id, { ...item, children: [] });
    });

    // 构建树
    items.forEach(item => {
      const node = map.get(item.id)!;
      if (item.parentId) {
        const parent = map.get(item.parentId);
        if (parent) {
          parent.children = parent.children || [];
          parent.children.push(node);
        }
      } else {
        roots.push(node);
      }
    });

    return roots;
  };

  const filteredCategories = categories.filter(cat => {
    const matchKeyword = !searchKeyword ||
      cat.name.includes(searchKeyword) ||
      cat.code.includes(searchKeyword);
    const matchType = typeFilter === 'all' || cat.type === typeFilter;
    return matchKeyword && matchType;
  });

  const treeData = buildTree(filteredCategories);

  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?: CategoryType) => {
    setEditingCategory(null);
    setParentCategory(parent || null);
    setFormData({
      code: '',
      name: '',
      type: parent?.type || 'industry',
      description: '',
      sortOrder: 0,
      isActive: true,
    });
    setShowDialog(true);
  };

  const handleEdit = (category: CategoryType) => {
    setEditingCategory(category);
    setParentCategory(null);
    setFormData({
      code: category.code,
      name: category.name,
      type: category.type,
      description: category.description || '',
      sortOrder: category.sortOrder,
      isActive: category.isActive,
    });
    setShowDialog(true);
  };

  const handleDelete = (id: string) => {
    // 检查是否有子分类
    const hasChildren = categories.some(cat => cat.parentId === id);
    if (hasChildren) {
      toast.error('请先删除子分类');
      return;
    }

    const updated = categories.filter(cat => cat.id !== id);
    saveCategories(updated);
    toast.success('删除成功');
  };

  const handleSave = () => {
    if (!formData.code.trim() || !formData.name.trim()) {
      toast.error('请填写编码和名称');
      return;
    }

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

    if (editingCategory) {
      // 编辑
      const updated = categories.map(cat =>
        cat.id === editingCategory.id
          ? {
              ...cat,
              ...formData,
              updatedAt: now,
            }
          : cat
      );
      saveCategories(updated);
      toast.success('更新成功');
    } else {
      // 新增
      const newCategory: CategoryType = {
        id: `cat-${Date.now()}`,
        ...formData,
        parentId: parentCategory?.id,
        level: parentCategory ? parentCategory.level + 1 : 1,
        createdAt: now,
        updatedAt: now,
      };
      saveCategories([...categories, newCategory]);
      toast.success('添加成功');
    }

    setShowDialog(false);
  };

  const renderTree = (nodes: CategoryType[], level: number = 0) => {
    return nodes.map(node => (
      <div key={node.id} style={{ marginLeft: `${level * 24}px` }}>
        <div className="flex items-center gap-2 py-2 px-3 hover:bg-gray-50 rounded-lg group">
          <div className="flex-1 flex items-center gap-2">
            {node.children && node.children.length > 0 ? (
              <button
                onClick={() => toggleExpand(node.id)}
                className="p-1 hover:bg-gray-200 rounded"
              >
                {expandedIds.has(node.id) ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
              </button>
            ) : (
              <div className="w-6" />
            )}
            {node.children && node.children.length > 0 ? (
              <Folder className="w-4 h-4 text-yellow-600" />
            ) : (
              <File className="w-4 h-4 text-gray-400" />
            )}
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span>{node.name}</span>
                <Badge variant="outline" className="text-xs">{node.code}</Badge>
                {!node.isActive && (
                  <Badge variant="outline" className="text-xs text-red-600">已停用</Badge>
                )}
              </div>
              {node.description && (
                <p className="text-xs text-muted-foreground">{node.description}</p>
              )}
            </div>
          </div>
          <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleAdd(node)}
            >
              <Plus className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEdit(node)}
            >
              <Edit className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDelete(node.id)}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        </div>
        {expandedIds.has(node.id) && node.children && renderTree(node.children, level + 1)}
      </div>
    ));
  };

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      industry: '行业类型',
      equipment: '设备类型',
      crop: '作物类型',
      operation: '作业类型',
      other: '其他',
    };
    return labels[type] || type;
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">分类字典</h2>
          <p className="text-muted-foreground">树形结构管理系统常用分类数据</p>
        </div>
        <Button onClick={() => handleAdd()}>
          <Plus className="w-4 h-4 mr-2" />
          新增分类
        </Button>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索分类名称、编码..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger>
              <SelectValue placeholder="分类类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="industry">行业类型</SelectItem>
              <SelectItem value="equipment">设备类型</SelectItem>
              <SelectItem value="crop">作物类型</SelectItem>
              <SelectItem value="operation">作业类型</SelectItem>
              <SelectItem value="other">其他</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 分类树 */}
      <Card className="p-4">
        <div className="min-h-[400px]">
          {treeData.length === 0 ? (
            <div className="text-center text-muted-foreground py-12">
              暂无分类数据
            </div>
          ) : (
            renderTree(treeData)
          )}
        </div>
      </Card>

      {/* 编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {editingCategory ? '编辑分类' : '新增分类'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingCategory ? '编辑分类信息' : '添加新分类'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {parentCategory && (
              <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <Label className="text-sm text-blue-900">上级分类</Label>
                <p className="mt-1">{parentCategory.name}</p>
              </div>
            )}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>分类编码 *</Label>
                <Input
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="IND001"
                />
              </div>
              <div>
                <Label>分类名称 *</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="请输入名称"
                />
              </div>
            </div>
            <div>
              <Label>分类类型</Label>
              <Select
                value={formData.type}
                onValueChange={(value) => setFormData({ ...formData, type: value })}
                disabled={!!parentCategory}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="industry">行业类型</SelectItem>
                  <SelectItem value="equipment">设备类型</SelectItem>
                  <SelectItem value="crop">作物类型</SelectItem>
                  <SelectItem value="operation">作业类型</SelectItem>
                  <SelectItem value="other">其他</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>描述</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="请输入描述"
                rows={3}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>排序</Label>
                <Input
                  type="number"
                  value={formData.sortOrder}
                  onChange={(e) => setFormData({ ...formData, sortOrder: parseInt(e.target.value) || 0 })}
                />
              </div>
              <div className="flex items-center justify-between pt-6">
                <Label>是否启用</Label>
                <Switch
                  checked={formData.isActive}
                  onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <FolderTree className="w-4 h-4 inline mr-2" />
          分类字典说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 支持多级树形结构，可无限级嵌套</li>
          <li>• 点击文件夹图标可展开/收起子分类</li>
          <li>• 鼠标悬停在分类上可显示操作按钮</li>
          <li>• 删除前需先删除所有子分类</li>
          <li>• 分类编码建议使用层级编码规则（如 IND001-01）</li>
        </ul>
      </Card>
    </div>
  );
}
