'use client';

import React, { useReducer, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { toast } from 'sonner';

import { CategoryDictionary, CategoryAction } from './types';
import { categoryReducer, initialState } from './reducer';
import { CategoryFilters } from './components/CategoryFilters';
import { CategoryTree } from './components/CategoryTree';
import { CategoryFormDialog } from './components/CategoryFormDialog';
import { CategoryInstructions } from './components/CategoryInstructions';

export default function CategoryDictionaryPage() {
  const [state, dispatch] = useReducer(categoryReducer, initialState);

  // 模拟数据加载
  useEffect(() => {
    const mockData: CategoryDictionary[] = [
      {
        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 加载数据
    const storedData = localStorage.getItem('smart_agriculture_category_dictionary');
    if (storedData) {
      try {
        const data = JSON.parse(storedData);
        dispatch({ type: 'SET_CATEGORIES', payload: data });
      } catch (error) {
        console.error('Failed to parse stored data:', error);
        dispatch({ type: 'SET_CATEGORIES', payload: mockData });
      }
    } else {
      dispatch({ type: 'SET_CATEGORIES', payload: mockData });
    }
  }, []);

  // 保存数据到 localStorage
  const saveCategories = (categories: CategoryDictionary[]) => {
    localStorage.setItem('smart_agriculture_category_dictionary', JSON.stringify(categories));
    dispatch({ type: 'SET_CATEGORIES', payload: categories });
  };

  // 构建树形结构
  const buildTree = (items: CategoryDictionary[]): CategoryDictionary[] => {
    const map = new Map<string, CategoryDictionary>();
    const roots: CategoryDictionary[] = [];

    // 创建映射
    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 = state.categories.filter(cat => {
    const matchKeyword = !state.searchKeyword ||
      cat.name.includes(state.searchKeyword) ||
      cat.code.includes(state.searchKeyword);
    const matchType = state.typeFilter === 'all' || cat.type === state.typeFilter;
    return matchKeyword && matchType;
  });

  const treeData = buildTree(filteredCategories);

  // 处理新增
  const handleAdd = (parent?: CategoryDictionary) => {
    dispatch({
      type: 'SET_DIALOG_STATE',
      payload: {
        open: true,
        editing: undefined,
        parent: parent || null,
      },
    });
  };

  // 处理编辑
  const handleEdit = (category: CategoryDictionary) => {
    dispatch({
      type: 'SET_DIALOG_STATE',
      payload: {
        open: true,
        editing: category,
        parent: undefined,
      },
    });
  };

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

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

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

    if (state.dialogState.editing) {
      // 编辑
      dispatch({
        type: 'UPDATE_CATEGORY',
        payload: {
          id: state.dialogState.editing.id,
          updates: state.formData,
        },
      });
      saveCategories(state.categories);
      toast.success('更新成功');
    } else {
      // 新增
      const newCategory: CategoryDictionary = {
        id: `cat-${Date.now()}`,
        ...state.formData,
        parentId: state.dialogState.parent?.id,
        level: state.dialogState.parent ? state.dialogState.parent.level + 1 : 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      dispatch({ type: 'ADD_CATEGORY', payload: newCategory });
      saveCategories([...state.categories, newCategory]);
      toast.success('添加成功');
    }

    dispatch({
      type: 'SET_DIALOG_STATE',
      payload: { open: false, editing: undefined, parent: undefined },
    });
  };

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

      {/* 搜索和筛选 */}
      <CategoryFilters
        searchKeyword={state.searchKeyword}
        typeFilter={state.typeFilter}
        onSearchChange={(value) => dispatch({ type: 'SET_SEARCH_KEYWORD', payload: value })}
        onTypeFilterChange={(value) => dispatch({ type: 'SET_TYPE_FILTER', payload: value })}
      />

      {/* 分类树 */}
      <CategoryTree
        categories={treeData}
        expandedIds={state.expandedIds}
        onToggleExpand={(id) => dispatch({ type: 'TOGGLE_EXPAND', payload: id })}
        onAdd={handleAdd}
        onEdit={handleEdit}
        onDelete={handleDelete}
      />

      {/* 编辑对话框 */}
      <CategoryFormDialog
        open={state.dialogState.open}
        editing={state.dialogState.editing}
        parent={state.dialogState.parent}
        formData={state.formData}
        onOpenChange={(open) => dispatch({
          type: 'SET_DIALOG_STATE',
          payload: { open, editing: undefined, parent: undefined },
        })}
        onFormDataChange={(data) => dispatch({ type: 'SET_FORM_DATA', payload: data })}
        onSave={handleSave}
      />

      {/* 使用说明 */}
      <CategoryInstructions />
    </div>
  );
}