import React, { useState, useEffect, useRef } from 'react';
import { Plus, Search, RefreshCw, ChevronRight, ChevronDown, Edit2, Trash2 } from 'lucide-react';
import { Modal, Switch as AntdSwitch } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button } from './ui/button';
import { Button as AntButton, Input, Space } from 'antd';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import PermissionWrapper from './PermissionWrapper';
import { deptApi, DeptVO } from '../api/dept';
import { userApi } from '../api/user';
import { UserVO } from '../types';
import { toast } from 'sonner';
import { DICT_TYPE, getIntDictOptions, getDictLabel, setDictOptions, DictDataType } from '../utils/dict';
import { dictDataApi } from '../api/DictData';
import { dateFormatter } from '../utils/formatTime';
import { handleTree, TreeNode } from '../utils/tree';
import DeptForm, { DeptFormRef } from './dept/DeptForm';
import { useTranslation } from 'react-i18next';
import './IsolationWorkListTable.css';

export default function DepartmentManagement() {
  const { t } = useTranslation();
  // “部门名称”列的统一偏移控制（表头/内容保持一致）
  const DEPT_COL_BASE_INDENT = 144; // 顶级行基础左内边距（表头也用同样值）
  const DEPT_COL_LEVEL_INDENT = 24; // 每层级缩进
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<TreeNode[]>([]);
  const [queryParams, setQueryParams] = useState({
    pageNo: 1,
    pageSize: 100,
    name: '',
    status: undefined as number | undefined,
  });
  const [isExpandAll, setIsExpandAll] = useState(true);
  const [expandedIds, setExpandedIds] = useState<number[]>([]);
  const [refreshTable, setRefreshTable] = useState(true);
  const [userList, setUserList] = useState<UserVO[]>([]);
  const [deptStatusUpdating, setDeptStatusUpdating] = useState<Record<number, boolean>>({});
  const [statusOptions, setStatusOptions] = useState(() => {
    try {
      return getIntDictOptions(DICT_TYPE.COMMON_STATUS);
    } catch (error) {
      console.error('获取字典选项失败:', error);
      return [];
    }
  });
  const formRef = useRef<DeptFormRef>(null);
  /** 部门树表格隔行底色（递归渲染时递增） */
  const zebraRowRef = useRef(0);

  // 加载 COMMON_STATUS 字典数据
  const loadCommonStatusDict = async () => {
    try {
      const response = await dictDataApi.getDictDataPage({
        pageNo: 1,
        pageSize: -1,
        dictType: DICT_TYPE.COMMON_STATUS,
      });
      const data = (response as any)?.data || response;
      const dictList = data?.list || [];
      if (Array.isArray(dictList) && dictList.length > 0) {
        const dictOptions: DictDataType[] = dictList.map((item: any) => ({
          dictType: item.dictType,
          label: item.label,
          value: item.value,
          colorType: item.colorType || '',
          cssClass: item.cssClass || '',
        }));
        setDictOptions(DICT_TYPE.COMMON_STATUS, dictOptions);
        // 更新状态选项
        setStatusOptions(getIntDictOptions(DICT_TYPE.COMMON_STATUS));
        console.log('DepartmentManagement: 获取通用状态字典成功', dictOptions);
      }
    } catch (error) {
      console.error('加载通用状态字典数据失败:', error);
    }
  };

  // 查询部门列表
  const getList = async () => {
    setLoading(true);
    try {
      const data = await deptApi.getDeptPage(queryParams);
      // 过滤掉没有 id 的项，并确保 id 存在
      const validDeptList = (data || []).filter((dept): dept is DeptVO & { id: number } => !!dept.id);
      const treeData = handleTree(validDeptList);
      setList(treeData);
      // 默认展开所有节点
      const allIds = getAllNodeIds(treeData);
      setExpandedIds(allIds);
    } catch (error: any) {
      console.error('获取部门列表失败:', error);
      toast.error(error.message || t('common.error'));
      setList([]); // 设置空数组，确保页面能显示
    } finally {
      setLoading(false);
    }
  };

  // 收集所有节点ID
  const getAllNodeIds = (nodes: TreeNode[]): number[] => {
    let ids: number[] = [];
    nodes.forEach(node => {
      ids.push(node.id);
      if (node.children && node.children.length > 0) {
        ids = ids.concat(getAllNodeIds(node.children));
      }
    });
    return ids;
  };

  // 展开/折叠操作
  const toggleExpandAll = () => {
    if (isExpandAll) {
      // 当前是展开状态，点击后折叠所有
      setExpandedIds([]);
    } else {
      // 当前是折叠状态，点击后展开所有
      setExpandedIds(getAllNodeIds(list));
    }
    setIsExpandAll(!isExpandAll);
  };

  // 切换单个节点的展开/折叠状态
  const toggleNode = (nodeId: number) => {
    setExpandedIds(prev =>
      prev.includes(nodeId) ? prev.filter(id => id !== nodeId) : [...prev, nodeId]
    );
  };

  // 搜索按钮操作
  const handleQuery = () => {
    getList();
  };

  // 重置按钮操作
  const resetQuery = () => {
    const resetParams = {
      pageNo: 1,
      pageSize: 100,
      name: '',
      status: undefined as number | undefined,
    };
    setQueryParams(resetParams);
    // 立即使用重置后的参数获取列表
    setLoading(true);
    deptApi.getDeptPage(resetParams)
      .then((data) => {
        // 过滤掉没有 id 的项，并确保 id 存在
        const validDeptList = (data || []).filter((dept): dept is DeptVO & { id: number } => !!dept.id);
        const treeData = handleTree(validDeptList);
        setList(treeData);
        // 默认展开所有节点
        const allIds = getAllNodeIds(treeData);
        setExpandedIds(allIds);
      })
      .catch((error: any) => {
        console.error('获取部门列表失败:', error);
        toast.error(error.message || t('common.error'));
        setList([]);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 添加/修改操作
  const openForm = (type: string, id?: number, parentId?: number) => {
    formRef.current?.open(type, id, parentId);
  };

  // 删除按钮操作
  const handleDelete = async (id: number, name: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('common.confirmDeleteText')} <strong>"{name}"</strong>?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDelete'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await deptApi.deleteDept(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 获取负责人名称
  const getLeaderName = (leaderUserId?: number): string => {
    if (!leaderUserId) return '';
    const user = userList.find((u) => u.id === leaderUserId);
    return user?.nickname || '';
  };

  // 处理状态变更
  const handleStatusChanged = async (dept: any, newStatus: number) => {
    if (!dept.id) {
      toast.error(t('common.error'));
      return;
    }

    setDeptStatusUpdating(prev => ({ ...prev, [dept.id!]: true }));

    try {
      const updatedDept: DeptVO = {
        id: dept.id,
        name: dept.name,
        parentId: dept.parentId ?? 0,
        sort: dept.sort ?? 0,
        leaderUserId: dept.leaderUserId,
        phone: dept.phone || '',
        email: dept.email || '',
        status: newStatus,
      };
      await deptApi.updateDept(updatedDept);
      toast.success(t('common.updateSuccess'));
      await getList();
    } catch (error: any) {
      toast.error(error.message || t('common.updateFailed'));
    } finally {
      setDeptStatusUpdating(prev => {
        const newState = { ...prev };
        delete newState[dept.id!];
        return newState;
      });
    }
  };

  // 递归渲染表格行
  const renderTableRows = (nodes: TreeNode[], level: number = 0): React.ReactNode[] => {
    if (level === 0) {
      zebraRowRef.current = 0;
    }
    return nodes.map((node) => {
      const hasChildren = node.children && node.children.length > 0;
      const isExpanded = expandedIds.includes(node.id);
      const isBuiltIn = !!(node as any).code && (node as any).code.trim() !== '';
      const stripeIdx = zebraRowRef.current++;

      return (
        <React.Fragment key={node.id}>
          <TableRow
            className={stripeIdx % 2 === 1 ? 'system-mgmt-row-alt hover:bg-gray-50' : 'hover:bg-gray-50'}
          >
            <TableCell
              style={{ paddingLeft: `${level * DEPT_COL_LEVEL_INDENT + DEPT_COL_BASE_INDENT}px` }}
              className="font-medium text-left"
            >
              <div className="flex items-center gap-2 justify-start">
                <span className="w-6 flex items-center justify-center flex-shrink-0">
                  {hasChildren ? (
                    <button
                      onClick={() => toggleNode(node.id)}
                      className="p-0.5 hover:bg-gray-200 rounded transition-colors"
                      aria-label={isExpanded ? t('common.collapse') : t('common.expand')}
                      type="button"
                    >
                      {isExpanded ? (
                        <ChevronDown className="w-4 h-4" />
                      ) : (
                        <ChevronRight className="w-4 h-4" />
                      )}
                    </button>
                  ) : null}
                </span>
                <span className="truncate ml-10">{(node as any).name || t('common.noData')}</span>
                {isBuiltIn && (
                  <span className="ml-1 px-2 py-0.5 text-xs font-semibold bg-red-500 text-white rounded flex-shrink-0">
                    {t('common.builtIn')}
                  </span>
                )}
              </div>
            </TableCell>
            <TableCell className="text-center">{node.id}</TableCell>
            <TableCell className="text-sm text-gray-600 text-center">{getLeaderName((node as any).leaderUserId) || '-'}</TableCell>
            <TableCell className="text-center">{(node as any).sort || 0}</TableCell>
            <TableCell className="text-center">
              {(() => {
                const status = Number((node as any).status);
                // 使用字典值显示状态
                const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
                // 根据字典的 label 来判断颜色：开启/启用显示绿色，禁用/关闭显示灰色
                const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
                const statusStyle = isEnabled 
                  ? 'bg-green-100 text-green-700' 
                  : 'bg-gray-100 text-gray-700';
                return (
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusStyle}`}>
                    {statusLabel}
                  </span>
                );
              })()}
            </TableCell>
            <TableCell className="text-sm text-gray-600 text-center">
              {(node as any).createTime ? dateFormatter((node as any).createTime) : '-'}
            </TableCell>
            <TableCell className="text-center">
              <div className="flex items-center gap-2 justify-center">
                <PermissionWrapper permission="system:dept:update">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => openForm('update', node.id)}
                    className="h-8 px-2 transition-colors hover:underline"
                    style={{ color: '#000000' }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = '#1677ff';
                      e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = '#000000';
                      e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                    }}
                  >
                    <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
                    <span className="ml-1">{t('common.edit')}</span>
                  </Button>
                </PermissionWrapper>
                <PermissionWrapper permission="system:dept:create">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => openForm('create', undefined, node.id)}
                    className="h-8 px-2 transition-colors hover:underline"
                    style={{ color: '#000000' }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = '#1677ff';
                      e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = '#000000';
                      e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                    }}
                  >
                    <Plus className="w-4 h-4" style={{ color: '#000000' }} />
                    <span className="ml-1">{t('common.addNew')}</span>
                  </Button>
                </PermissionWrapper>
                <PermissionWrapper permission="system:dept:delete">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleDelete(node.id, (node as any).name || '未命名部门')}
                    className={`h-8 px-2 transition-colors hover:underline ${isBuiltIn ? 'text-gray-400 cursor-not-allowed' : ''}`}
                    disabled={isBuiltIn}
                    style={{ color: isBuiltIn ? '#9ca3af' : '#000000' }}
                    onMouseEnter={(e) => {
                      if (!isBuiltIn) {
                        e.currentTarget.style.color = '#1677ff';
                        e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!isBuiltIn) {
                        e.currentTarget.style.color = '#000000';
                        e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                      }
                    }}
                  >
                    <Trash2 className="w-4 h-4" style={{ color: isBuiltIn ? '#9ca3af' : '#000000' }} />
                    <span className="ml-1">{t('common.delete')}</span>
                  </Button>
                </PermissionWrapper>
              </div>
            </TableCell>
          </TableRow>
          {hasChildren && isExpanded && renderTableRows(node.children!, level + 1)}
        </React.Fragment>
      );
    });
  };

  // 初始化
  useEffect(() => {
    console.log('DepartmentManagement 组件已挂载，开始获取数据');
    const initData = async () => {
      try {
        // 先加载字典数据
        await loadCommonStatusDict();
        console.log('开始调用 getList() 获取部门列表');
        await getList();
        console.log('部门列表获取成功');
      } catch (error) {
        console.error('获取部门列表失败:', error);
        // 即使失败也设置 loading 为 false，显示页面
        setLoading(false);
      }
      // 获取用户列表
      try {
        console.log('开始获取用户列表');
        const users = await userApi.getSimpleUserList();
        setUserList(users);
        console.log('用户列表获取成功，用户数量:', users.length);
      } catch (error) {
        console.error('获取用户列表失败:', error);
      }
    };
    initData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="space-y-4">
      {/* 搜索栏 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-4 lg:p-5">
        <div className="flex items-center justify-between gap-3 lg:gap-4 flex-wrap min-w-0">
          {/* 搜索条件 + 搜索、重置紧跟其后 */}
          <div className="flex items-center gap-2 lg:gap-3 flex-wrap min-w-0">
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.departmentName')}：</label>
              <Input
                value={queryParams.name || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, name: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.departmentNamePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="system:dept:query">
                <AntButton
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </AntButton>
              </PermissionWrapper>
              
              <PermissionWrapper permission="system:dept:query">
                <AntButton
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </AntButton>
              </PermissionWrapper>
            </Space>
          </div>

          {/* 新增、展开等按钮组保持在最右侧 */}
          <Space className="flex-shrink-0" size="small">
            <PermissionWrapper permission="system:dept:create">
              <AntButton
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </AntButton>
            </PermissionWrapper>
            
            <AntButton
              icon={isExpandAll ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
              onClick={toggleExpandAll}
            >
              {isExpandAll ? t('common.collapse') : t('common.expand')}
            </AntButton>
          </Space>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        {refreshTable && (
          <div className="system-mgmt-shadcn-table">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead
                  className="w-[250px] text-left"
                  style={{ paddingLeft: `${DEPT_COL_BASE_INDENT}px` }}
                >
                  {t('table.departmentName')}
                </TableHead>
                <TableHead className="w-[100px] text-center">部门id</TableHead>
                <TableHead className="w-[150px] text-center">{t('table.leader')}</TableHead>
                <TableHead className="w-[80px] text-center">{t('table.sort')}</TableHead>
                <TableHead className="w-[100px] text-center">{t('table.status')}</TableHead>
                <TableHead className="w-[180px] text-center">{t('table.createTime')}</TableHead>
                <TableHead className="w-[220px] text-center">{t('table.operation')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                    {t('common.loading')}
                  </TableCell>
                </TableRow>
              ) : list.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                    {t('common.noData')}
                  </TableCell>
                </TableRow>
              ) : (
                renderTableRows(list)
              )}
            </TableBody>
          </Table>
          </div>
        )}
      </div>

      {/* 表单弹窗 */}
      <DeptForm ref={formRef} onSuccess={getList} />
    </div>
  );
}
