import React, { useState, useEffect, useRef } from 'react';
import { Search, Plus, RefreshCw, Edit2, Trash2, Download, Settings, Shield } from 'lucide-react';
import { roleApi, RoleVO, PageParam } from '../api/Role';
import { toast } from 'sonner';
import { formatDateTimeFull } from '../utils/formatTime';
import { getIntDictOptions, DICT_TYPE, getDictLabel, getDictOptions, setDictOptions, DictDataType } from '../utils/dict';
import { dictDataApi } from '../api/DictData';
import { Modal, Button, Input, Space, Tooltip } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from './ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import RoleForm, { RoleFormRef } from './RoleForm';
import RoleAssignMenuForm, { RoleAssignMenuFormRef } from './RoleAssignMenuForm';
import RoleDataPermissionForm, { RoleDataPermissionFormRef } from './RoleDataPermissionForm';
import PermissionWrapper from './PermissionWrapper';
import { hasPermission } from '../utils/permission';
import { useTranslation } from 'react-i18next';
import './IsolationWorkListTable.css';

export default function RoleManagement() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<RoleVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<PageParam>({
    pageNo: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
  });
  const [exportLoading, setExportLoading] = useState(false);
  const formRef = useRef<RoleFormRef>(null);
  const assignMenuFormRef = useRef<RoleAssignMenuFormRef>(null);
  const dataPermissionFormRef = useRef<RoleDataPermissionFormRef>(null);

  // 加载字典数据
  const loadDictData = async () => {
    try {
      // 并行加载角色类型和通用状态字典
      const [roleTypeResponse, commonStatusResponse] = await Promise.all([
        dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: DICT_TYPE.SYSTEM_ROLE_TYPE,
        }),
        dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: DICT_TYPE.COMMON_STATUS,
        }),
      ]);

      // 处理角色类型字典
      const roleTypeData = (roleTypeResponse as any)?.data || roleTypeResponse;
      const roleTypeList = roleTypeData?.list || [];
      if (Array.isArray(roleTypeList) && roleTypeList.length > 0) {
        const roleTypeOptions: DictDataType[] = roleTypeList.map((item: any) => ({
          dictType: item.dictType,
          label: item.label,
          value: item.value,
          colorType: item.colorType || '',
          cssClass: item.cssClass || '',
        }));
        setDictOptions(DICT_TYPE.SYSTEM_ROLE_TYPE, roleTypeOptions);
        console.log('RoleManagement: 获取角色类型字典成功', roleTypeOptions);
      }

      // 处理通用状态字典
      const commonStatusData = (commonStatusResponse as any)?.data || commonStatusResponse;
      const commonStatusList = commonStatusData?.list || [];
      if (Array.isArray(commonStatusList) && commonStatusList.length > 0) {
        const commonStatusOptions: DictDataType[] = commonStatusList.map((item: any) => ({
          dictType: item.dictType,
          label: item.label,
          value: item.value,
          colorType: item.colorType || '',
          cssClass: item.cssClass || '',
        }));
        setDictOptions(DICT_TYPE.COMMON_STATUS, commonStatusOptions);
        console.log('RoleManagement: 获取通用状态字典成功', commonStatusOptions);
      }
    } catch (error) {
      console.error('加载字典数据失败:', error);
    }
  };

  // 获取角色列表
  const getList = async (params?: PageParam) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      const response = await roleApi.getRolePage(currentParams);
      const data = (response as any)?.data || response;
      
      if (!data || typeof data !== 'object') {
        setList([]);
        setTotal(0);
        return;
      }
      
      setList(data.list || []);
      setTotal(data.total || 0);
    } catch (error: any) {
      console.error('获取角色列表失败', error);
      setList([]);
      setTotal(0);
      const errorMessage = error?.response?.data?.message || error?.message || '获取角色列表失败';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载字典数据
  useEffect(() => {
    loadDictData();
  }, []);

  // 组件挂载和分页参数变化时获取数据
  useEffect(() => {
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.pageNo, queryParams.pageSize]);

  // 搜索
  const handleQuery = () => {
    const newParams = { ...queryParams, pageNo: 1 };
    setQueryParams(newParams);
    getList(newParams);
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: PageParam = {
      pageNo: 1,
      pageSize: 10,
      name: undefined,
      code: undefined,
    };
    // 先设置状态，确保搜索框能同步更新
    setQueryParams(resetParams);
    // 使用重置后的参数立即获取列表
    getList(resetParams);
  };

  // 打开表单
  const openForm = (type: string, id?: number) => {
    if (formRef.current) {
      formRef.current.open(type, id);
    }
  };

  // 打开菜单权限表单
  const openAssignMenuForm = (row: RoleVO) => {
    if (assignMenuFormRef.current) {
      assignMenuFormRef.current.open(row);
    }
  };

  // 打开数据权限表单
  const openDataPermissionForm = (row: RoleVO) => {
    if (dataPermissionFormRef.current) {
      dataPermissionFormRef.current.open(row);
    }
  };

  // 删除角色
  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 roleApi.deleteRole(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 导出角色
  const handleExport = async () => {
    Modal.confirm({
      title: t('role.exportConfirm'),
      icon: <ExclamationCircleOutlined />,
      content: t('role.exportConfirmText'),
      okText: t('role.exportConfirmButton'),
      cancelText: t('common.cancel'),
      onOk: async () => {
        setExportLoading(true);
        try {
          const response = await roleApi.exportRole(queryParams);
          const blob = (response as any)?.data || response;
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = t('role.exportFileName');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          toast.success(t('role.exportSuccess'));
        } catch (error: any) {
          toast.error(error.message || t('role.exportFailed'));
        } finally {
          setExportLoading(false);
        }
      },
    });
  };


  // 获取状态标签（使用字典值）
  const getStatusLabel = (status: number) => {
    return getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
  };

  // 获取状态样式（使用字典值）
  const getStatusStyle = (status: number) => {
    const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
    // 根据字典的 label 来判断颜色：开启/启用显示绿色，禁用/关闭显示灰色
    const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
    return isEnabled 
      ? 'bg-green-100 text-green-700' 
      : 'bg-gray-100 text-gray-700';
  };

  // 获取角色类型标签
  const getRoleTypeLabel = (type: number) => {
    return getDictLabel(DICT_TYPE.SYSTEM_ROLE_TYPE, type) || t('role.unknown');
  };

  // 是否为内置角色（内置角色不可操作）
  const isBuiltInRole = (row: RoleVO) => {
    const typeLabel = getRoleTypeLabel(row.type) || '';
    return typeLabel === '内置' || typeLabel === 'Built-in' || (row as any).builtIn === true;
  };

  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.roleName')}：</label>
              <Input
                value={queryParams.name || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, name: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.roleNamePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <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.roleCode')}：</label>
              <Input
                value={queryParams.code || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, code: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.roleCodePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="system:role:query">
                <Button
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </Button>
              </PermissionWrapper>
              
              <PermissionWrapper permission="system:role:query">
                <Button
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>

          {/* 新增、导出等按钮组保持在最右侧 */}
          <Space className="flex-shrink-0" size="small">
            <PermissionWrapper permission="system:role:create">
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </Button>
            </PermissionWrapper>
            
            <PermissionWrapper permission="system:role:export">
              <Button
                icon={<Download className="w-4 h-4" />}
                onClick={handleExport}
                loading={exportLoading}
              >
                {t('common.export')}
              </Button>
            </PermissionWrapper>
          </Space>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <div className="system-mgmt-shadcn-table">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[100px] text-center">{t('table.roleId')}</TableHead>
              <TableHead className="w-[150px]">{t('table.roleName')}</TableHead>
              <TableHead className="w-[120px] text-center">{t('table.status')}</TableHead>
              <TableHead className="w-[150px]">{t('table.roleCode')}</TableHead>
              <TableHead className="w-[100px] text-center">{t('table.sort')}</TableHead>
              <TableHead>{t('table.remark')}</TableHead>
              <TableHead className="w-[100px] text-center">{t('table.status')}</TableHead>
              <TableHead className="w-[180px] text-center">{t('table.createTime')}</TableHead>
              <TableHead className="w-[350px] text-center">{t('table.operation')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center py-8 text-gray-500">
                  {t('role.loading')}
                </TableCell>
              </TableRow>
            ) : list.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center py-8 text-gray-500">
                  {t('role.noData')}
                </TableCell>
              </TableRow>
            ) : (
              list.map((row, index) => (
                <TableRow
                  key={row.id}
                  className={index % 2 === 1 ? 'system-mgmt-row-alt hover:bg-gray-50' : 'hover:bg-gray-50'}
                >
                  <TableCell className="text-center">{row.id}</TableCell>
                  <TableCell className="font-medium">{row.name}</TableCell>
                  <TableCell className="text-center text-sm">
                    {getRoleTypeLabel(row.type)}
                  </TableCell>
                  <TableCell>{row.code}</TableCell>
                  <TableCell className="text-center">{row.sort}</TableCell>
                  <TableCell className="text-sm text-gray-600">
                    {(() => {
                      const text = row.remark || '-';
                      const maxLength = 20;
                      const shouldTruncate = text.length > maxLength;
                      const displayText = shouldTruncate ? text.slice(0, maxLength) + '...' : text;
                      
                      return (
                        <Tooltip placement="topLeft" title={text}>
                          <span>{displayText}</span>
                        </Tooltip>
                      );
                    })()}
                  </TableCell>
                  <TableCell className="text-center">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(row.status)}`}>
                      {getStatusLabel(row.status)}
                    </span>
                  </TableCell>
                  <TableCell className="text-center text-sm text-gray-600">
                    {formatDateTimeFull(row.createTime)}
                  </TableCell>
                  <TableCell>
                    <Tooltip title={isBuiltInRole(row) ? t('role.builtInNoOperation') : undefined}>
                      <div className={`flex items-center gap-2 justify-center ${isBuiltInRole(row) ? 'pointer-events-none opacity-50' : ''}`}>
                        <PermissionWrapper permission="system:role:update">
                          <UIButton
                            variant="ghost"
                            size="sm"
                            disabled={isBuiltInRole(row)}
                            onClick={() => !isBuiltInRole(row) && openForm('update', row.id)}
                            className="h-8 px-2 transition-colors hover:underline"
                            style={{ color: '#000000' }}
                            onMouseEnter={(e) => {
                              if (isBuiltInRole(row)) return;
                              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>
                          </UIButton>
                        </PermissionWrapper>
                        <PermissionWrapper permission="system:permission:assign-role-menu">
                          <UIButton
                            variant="ghost"
                            size="sm"
                            disabled={isBuiltInRole(row)}
                            onClick={() => !isBuiltInRole(row) && openAssignMenuForm(row)}
                            className="h-8 px-2 transition-colors hover:underline"
                            style={{ color: '#000000' }}
                            onMouseEnter={(e) => {
                              if (isBuiltInRole(row)) return;
                              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');
                            }}
                          >
                            <Settings className="w-4 h-4" style={{ color: '#000000' }} />
                            <span className="ml-1">{t('role.menuPermission')}</span>
                          </UIButton>
                        </PermissionWrapper>
                        <PermissionWrapper permission="system:permission:assign-role-data-scope">
                          <UIButton
                            variant="ghost"
                            size="sm"
                            disabled={isBuiltInRole(row)}
                            onClick={() => !isBuiltInRole(row) && openDataPermissionForm(row)}
                            className="h-8 px-2 transition-colors hover:underline"
                            style={{ color: '#000000' }}
                            onMouseEnter={(e) => {
                              if (isBuiltInRole(row)) return;
                              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');
                            }}
                          >
                            <Shield className="w-4 h-4" style={{ color: '#000000' }} />
                            <span className="ml-1">{t('role.dataPermission')}</span>
                          </UIButton>
                        </PermissionWrapper>
                        <PermissionWrapper permission="system:role:delete">
                          <UIButton
                            variant="ghost"
                            size="sm"
                            disabled={isBuiltInRole(row)}
                            onClick={() => !isBuiltInRole(row) && handleDelete(row.id!, row.name)}
                            className="h-8 px-2 transition-colors hover:underline"
                            style={{ color: '#000000' }}
                            onMouseEnter={(e) => {
                              if (isBuiltInRole(row)) return;
                              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');
                            }}
                          >
                            <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
                            <span className="ml-1">{t('common.delete')}</span>
                          </UIButton>
                        </PermissionWrapper>
                      </div>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
        </div>
      </div>

      {/* 分页 */}
      {!loading && list.length > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('role.totalRecords')} <span className="text-blue-600 font-medium">{total}</span> {t('role.records')}
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! - 1 })}
                disabled={queryParams.pageNo! <= 1}
              >
                {t('role.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize!) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! + 1 })}
                disabled={queryParams.pageNo! >= Math.ceil(total / queryParams.pageSize!)}
              >
                {t('role.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 表单弹窗 */}
      <RoleForm ref={formRef} onSuccess={getList} />
      <RoleAssignMenuForm ref={assignMenuFormRef} onSuccess={getList} />
      <RoleDataPermissionForm ref={dataPermissionFormRef} onSuccess={getList} />
    </div>
  );
}

