/**
 * KRA - API Permission Component
 * Configure API permissions for authority/role
 */
import React, { useState, useEffect } from 'react';
import { Tree, Input, Button, message, Tooltip } from 'antd';
import type { DataNode, TreeProps } from 'antd/es/tree';
import { getAllApis } from '@/services/kratos/api';
import { updateCasbin, getPolicyPathByAuthorityId } from '@/services/kratos/casbin';

const { Search } = Input;

interface Authority {
  authorityId: string;
  authorityName: string;
}

interface ApiInfo {
  ID: number;
  path: string;
  method: string;
  apiGroup: string;
  description: string;
}

interface ApiPermissionProps {
  row: Authority;
}

const ApiPermission: React.FC<ApiPermissionProps> = ({ row }) => {
  const [apiTreeData, setApiTreeData] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [filterTextName, setFilterTextName] = useState('');
  const [filterTextPath, setFilterTextPath] = useState('');
  const [loading, setLoading] = useState(false);
  const [apiMap, setApiMap] = useState<Map<string, ApiInfo>>(new Map());

  useEffect(() => {
    fetchApiData();
  }, [row.authorityId]);

  const fetchApiData = async () => {
    setLoading(true);
    try {
      // 获取所有 API
      const apiRes = await getAllApis();
      const apis: ApiInfo[] = apiRes.data?.apis || [];

      // 构建 API 映射
      const map = new Map<string, ApiInfo>();
      apis.forEach((api) => {
        const key = `p:${api.path}m:${api.method}`;
        map.set(key, api);
      });
      setApiMap(map);

      // 按 apiGroup 分组构建树
      const treeData = buildApiTree(apis);
      setApiTreeData(treeData);

      // 展开所有分组
      const groupKeys = [...new Set(apis.map((api) => api.apiGroup))];
      setExpandedKeys(groupKeys);

      // 获取当前角色的 API 权限
      const policyRes = await getPolicyPathByAuthorityId({ authorityId: row.authorityId });
      const paths = policyRes.data?.paths || [];
      const checkedIds = paths.map((item) => `p:${item.path}m:${item.method}`);
      setCheckedKeys(checkedIds);
    } catch (error) {
      console.error('Failed to fetch API data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 构建 API 树
  const buildApiTree = (apis: ApiInfo[]): DataNode[] => {
    const groupMap = new Map<string, ApiInfo[]>();
    
    apis.forEach((api) => {
      const group = api.apiGroup || '未分组';
      if (!groupMap.has(group)) {
        groupMap.set(group, []);
      }
      groupMap.get(group)!.push(api);
    });

    const treeData: DataNode[] = [];
    groupMap.forEach((groupApis, groupName) => {
      treeData.push({
        key: groupName,
        title: `${groupName}组`,
        children: groupApis.map((api) => ({
          key: `p:${api.path}m:${api.method}`,
          title: (
            <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', paddingRight: 8 }}>
              <span>{api.description}</span>
              <Tooltip title={api.path}>
                <span style={{ 
                  maxWidth: 240, 
                  overflow: 'hidden', 
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  color: '#999',
                }}>
                  {api.path}
                </span>
              </Tooltip>
            </div>
          ),
        })),
      });
    });

    return treeData;
  };

  // 确认 API 权限
  const handleConfirm = async () => {
    try {
      // 过滤出实际的 API 节点（排除分组节点）
      const casbinInfos = checkedKeys
        .filter((key) => typeof key === 'string' && key.startsWith('p:'))
        .map((key) => {
          const keyStr = key as string;
          const pathMatch = keyStr.match(/p:(.+)m:/);
          const methodMatch = keyStr.match(/m:(.+)$/);
          return {
            path: pathMatch ? pathMatch[1] : '',
            method: methodMatch ? methodMatch[1] : '',
          };
        })
        .filter((info) => info.path && info.method);

      const res = await updateCasbin({
        authorityId: row.authorityId,
        casbinInfos,
      });
      if (res.code === 0) {
        message.success('API设置成功');
      }
    } catch (error) {
      message.error('设置失败');
    }
  };

  // 处理选中变化
  const handleCheck: TreeProps['onCheck'] = (checked, info) => {
    setCheckedKeys(checked as React.Key[]);
  };

  // 过滤节点
  const filterTreeNode = (node: DataNode): boolean => {
    if (!filterTextName && !filterTextPath) return true;
    
    const key = node.key as string;
    const api = apiMap.get(key);
    
    if (!api) {
      // 分组节点，检查是否有子节点匹配
      return true;
    }

    let matchesName = true;
    let matchesPath = true;

    if (filterTextName) {
      matchesName = api.description?.toLowerCase().includes(filterTextName.toLowerCase()) || false;
    }
    if (filterTextPath) {
      matchesPath = api.path?.toLowerCase().includes(filterTextPath.toLowerCase()) || false;
    }

    return matchesName && matchesPath;
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, position: 'sticky', top: 0, background: '#fff', zIndex: 10, padding: '8px 0' }}>
        <Search
          placeholder="筛选名字"
          value={filterTextName}
          onChange={(e) => setFilterTextName(e.target.value)}
          style={{ flex: 1 }}
        />
        <Search
          placeholder="筛选路径"
          value={filterTextPath}
          onChange={(e) => setFilterTextPath(e.target.value)}
          style={{ flex: 1 }}
        />
        <Button type="primary" onClick={handleConfirm}>
          确定
        </Button>
      </div>
      <div style={{ maxHeight: 'calc(100vh - 300px)', overflow: 'auto' }}>
        <Tree
          checkable
          defaultExpandAll
          expandedKeys={expandedKeys}
          onExpand={setExpandedKeys}
          checkedKeys={checkedKeys}
          onCheck={handleCheck}
          treeData={apiTreeData}
          filterTreeNode={filterTreeNode}
        />
      </div>
    </div>
  );
};

export default ApiPermission;
