/**
 * KRA - API Management Page
 * Manage system APIs with CRUD operations
 */
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag, Space, Select, Input, Form, Drawer, Modal } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SyncOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import {
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  deleteApisByIds,
  freshCasbin,
  syncApi,
  getApiGroups,
  getApiById,
} from '@/services/kratos/api';
import WarningBar from '@/components/WarningBar/WarningBar';
import ApiForm from './components/ApiForm';
import ApiSync from './components/ApiSync';

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

const methodOptions = [
  { value: 'POST', label: '创建', color: 'green' },
  { value: 'GET', label: '查看', color: 'blue' },
  { value: 'PUT', label: '更新', color: 'orange' },
  { value: 'DELETE', label: '删除', color: 'red' },
];

const ApiPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [syncDrawerVisible, setSyncDrawerVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<ApiItem | null>(null);
  const [dialogFlag, setDialogFlag] = useState<'add' | 'edit'>('add');
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [apiGroupOptions, setApiGroupOptions] = useState<{ label: string; value: string }[]>([]);
  const [syncData, setSyncData] = useState<any>(null);

  // 获取API分组
  const fetchApiGroups = async () => {
    try {
      const res = await getApiGroups();
      if (res.code === 0) {
        const groups = res.data?.groups || [];
        setApiGroupOptions(groups.map((g: string) => ({ label: g, value: g })));
      }
    } catch (error) {
      console.error('Failed to fetch API groups:', error);
    }
  };

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

  // 获取方法标签
  const getMethodTag = (method: string) => {
    const option = methodOptions.find((m) => m.value === method);
    return option ? (
      <Tag color={option.color}>
        {method} / {option.label}
      </Tag>
    ) : (
      <Tag>{method}</Tag>
    );
  };

  // 编辑API
  const handleEdit = async (record: ApiItem) => {
    try {
      const res = await getApiById({ id: record.ID });
      if (res.code === 0 && res.data?.api) {
        setCurrentRow(res.data.api);
        setDialogFlag('edit');
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取API信息失败');
    }
  };

  // 删除API
  const handleDelete = async (record: ApiItem) => {
    try {
      const res = await deleteApi({ ID: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        actionRef.current?.reload();
        fetchApiGroups();
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的API');
      return;
    }
    Modal.confirm({
      title: '确定要删除选中的API吗?',
      content: `将删除 ${selectedRowKeys.length} 条API记录`,
      onOk: async () => {
        try {
          const res = await deleteApisByIds({ ids: selectedRowKeys });
          if (res.code === 0) {
            message.success(res.msg || '删除成功');
            setSelectedRowKeys([]);
            actionRef.current?.reload();
            fetchApiGroups();
          } else {
            message.error(res.msg || '删除失败');
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 刷新缓存
  const handleFreshCasbin = async () => {
    Modal.confirm({
      title: '确定要刷新缓存吗?',
      onOk: async () => {
        try {
          const res = await freshCasbin();
          if (res.code === 0) {
            message.success(res.msg || '刷新成功');
          } else {
            message.error(res.msg || '刷新失败');
          }
        } catch (error) {
          message.error('刷新失败');
        }
      },
    });
  };

  // 同步API
  const handleSyncApi = async () => {
    try {
      const res = await syncApi();
      if (res.code === 0) {
        setSyncData(res.data);
        setSyncDrawerVisible(true);
      } else {
        message.error(res.msg || '同步失败');
      }
    } catch (error) {
      message.error('同步失败');
    }
  };

  // 表格列定义
  const columns: ProColumns<ApiItem>[] = [
    {
      title: 'ID',
      dataIndex: 'ID',
      width: 80,
      sorter: true,
    },
    {
      title: 'API路径',
      dataIndex: 'path',
      width: 200,
      ellipsis: true,
      sorter: true,
    },
    {
      title: 'API分组',
      dataIndex: 'apiGroup',
      width: 150,
      sorter: true,
      valueType: 'select',
      fieldProps: {
        options: apiGroupOptions,
      },
    },
    {
      title: 'API简介',
      dataIndex: 'description',
      width: 200,
      ellipsis: true,
      sorter: true,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 150,
      sorter: true,
      valueType: 'select',
      fieldProps: {
        options: methodOptions.map((m) => ({ label: `${m.label}(${m.value})`, value: m.value })),
      },
      render: (_, record) => getMethodTag(record.method),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="此操作将永久删除所有角色下该API, 是否继续?"
          onConfirm={() => handleDelete(record)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" size="small" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <WarningBar title="新增API，需要在角色管理内配置权限才可使用" type="warning" />
      <ProTable<ApiItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="ID"
        scroll={{ x: 1000 }}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        request={async (params, sort) => {
          const sortKey = Object.keys(sort || {})[0];
          const res = await getApiList({
            page: params.current || 1,
            pageSize: params.pageSize || 10,
            path: params.path,
            description: params.description,
            apiGroup: params.apiGroup,
            method: params.method,
            orderKey: sortKey,
            desc: sort?.[sortKey] === 'descend',
          });
          return {
            data: res.data?.list || [],
            total: res.data?.total || 0,
            success: res.code === 0,
          };
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '30', '50', '100'],
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCurrentRow(null);
              setDialogFlag('add');
              setDrawerVisible(true);
            }}
          >
            新增
          </Button>,
          <Button
            key="delete"
            icon={<DeleteOutlined />}
            disabled={selectedRowKeys.length === 0}
            onClick={handleBatchDelete}
          >
            删除
          </Button>,
          <Button key="refresh" icon={<ReloadOutlined />} onClick={handleFreshCasbin}>
            刷新缓存
          </Button>,
          <Button key="sync" icon={<SyncOutlined />} onClick={handleSyncApi}>
            同步API
          </Button>,
        ]}
        search={{
          labelWidth: 'auto',
        }}
      />

      {/* API表单抽屉 */}
      <ApiForm
        visible={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
        }}
        onSuccess={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
          actionRef.current?.reload();
          fetchApiGroups();
        }}
        initialValues={currentRow}
        dialogFlag={dialogFlag}
        apiGroupOptions={apiGroupOptions}
      />

      {/* API同步抽屉 */}
      <ApiSync
        visible={syncDrawerVisible}
        onClose={() => {
          setSyncDrawerVisible(false);
          setSyncData(null);
        }}
        onSuccess={() => {
          setSyncDrawerVisible(false);
          setSyncData(null);
          actionRef.current?.reload();
          fetchApiGroups();
        }}
        syncData={syncData}
        apiGroupOptions={apiGroupOptions}
      />
    </PageContainer>
  );
};

export default ApiPage;
