/**
 * KRA - API Sync Drawer Component
 * Synchronize APIs from backend routes
 */
import React, { useState, useEffect } from 'react';
import { Drawer, Table, Button, Space, Select, Input, Tag, message, Typography } from 'antd';
import { PlusOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import { createApi, ignoreApi, enterSyncApi } from '@/services/kratos/api';
import WarningBar from '@/components/WarningBar/WarningBar';

const { Title, Text } = Typography;

interface SyncApiItem {
  path: string;
  method: string;
  apiGroup?: string;
  description?: string;
}

interface SyncData {
  newApis: SyncApiItem[];
  deleteApis: SyncApiItem[];
  ignoreApis: SyncApiItem[];
}

interface ApiSyncProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  syncData: SyncData | null;
  apiGroupOptions: { label: string; value: string }[];
}

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

const ApiSync: React.FC<ApiSyncProps> = ({
  visible,
  onClose,
  onSuccess,
  syncData,
  apiGroupOptions,
}) => {
  const [loading, setLoading] = useState(false);
  const [newApis, setNewApis] = useState<SyncApiItem[]>([]);
  const [deleteApis, setDeleteApis] = useState<SyncApiItem[]>([]);
  const [ignoreApis, setIgnoreApis] = useState<SyncApiItem[]>([]);

  // 初始化数据
  useEffect(() => {
    if (visible && syncData) {
      setNewApis(syncData.newApis || []);
      setDeleteApis(syncData.deleteApis || []);
      setIgnoreApis(syncData.ignoreApis || []);
    }
  }, [visible, syncData]);

  // 获取方法标签
  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 handleUpdateNewApi = (index: number, field: string, value: string) => {
    const updated = [...newApis];
    (updated[index] as any)[field] = value;
    setNewApis(updated);
  };

  // 单条新增API
  const handleAddSingleApi = async (record: SyncApiItem, index: number) => {
    if (!record.apiGroup) {
      message.error('请先选择API分组');
      return;
    }
    if (!record.description) {
      message.error('请先填写API描述');
      return;
    }

    try {
      const res = await createApi({
        path: record.path,
        method: record.method,
        apiGroup: record.apiGroup,
        description: record.description,
      });
      if (res.code === 0) {
        message.success('添加成功，请到角色管理页面分配权限');
        // 从列表中移除
        const updated = newApis.filter((_, i) => i !== index);
        setNewApis(updated);
      } else {
        message.error(res.msg || '添加失败');
      }
    } catch (error) {
      message.error('添加失败');
    }
  };

  // 忽略API
  const handleIgnoreApi = async (record: SyncApiItem, index: number, ignore: boolean) => {
    try {
      const res = await ignoreApi({
        path: record.path,
        method: record.method,
        flag: ignore,
      });
      if (res.code === 0) {
        message.success(res.msg || (ignore ? '已忽略' : '已取消忽略'));
        if (ignore) {
          // 从新增列表移到忽略列表
          const updated = newApis.filter((_, i) => i !== index);
          setNewApis(updated);
          setIgnoreApis([...ignoreApis, record]);
        } else {
          // 从忽略列表移到新增列表
          const updated = ignoreApis.filter((_, i) => i !== index);
          setIgnoreApis(updated);
          setNewApis([...newApis, record]);
        }
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 确认同步
  const handleConfirmSync = async () => {
    // 检查是否有未填写的API
    const incomplete = newApis.some((api) => !api.apiGroup || !api.description);
    if (incomplete) {
      message.error('存在API未分组或未填写描述');
      return;
    }

    setLoading(true);
    try {
      const res = await enterSyncApi({
        newApis,
        deleteApis,
        ignoreApis,
      });
      if (res.code === 0) {
        message.success(res.msg || '同步成功');
        onSuccess();
      } else {
        message.error(res.msg || '同步失败');
      }
    } catch (error) {
      message.error('同步失败');
    } finally {
      setLoading(false);
    }
  };

  // 新增API表格列
  const newApiColumns = [
    {
      title: 'API路径',
      dataIndex: 'path',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'API分组',
      dataIndex: 'apiGroup',
      width: 150,
      render: (_: any, record: SyncApiItem, index: number) => (
        <Select
          value={record.apiGroup}
          onChange={(v) => handleUpdateNewApi(index, 'apiGroup', v)}
          placeholder="请选择或新增"
          options={apiGroupOptions}
          showSearch
          allowClear
          style={{ width: '100%' }}
          size="small"
        />
      ),
    },
    {
      title: 'API简介',
      dataIndex: 'description',
      width: 200,
      render: (_: any, record: SyncApiItem, index: number) => (
        <Input
          value={record.description}
          onChange={(e) => handleUpdateNewApi(index, 'description', e.target.value)}
          placeholder="请输入API简介"
          size="small"
        />
      ),
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 120,
      render: (_: any, record: SyncApiItem) => getMethodTag(record.method),
    },
    {
      title: '操作',
      width: 180,
      render: (_: any, record: SyncApiItem, index: number) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<PlusOutlined />}
            onClick={() => handleAddSingleApi(record, index)}
          >
            单条新增
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EyeInvisibleOutlined />}
            onClick={() => handleIgnoreApi(record, index, true)}
          >
            忽略
          </Button>
        </Space>
      ),
    },
  ];

  // 删除API表格列
  const deleteApiColumns = [
    {
      title: 'API路径',
      dataIndex: 'path',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'API分组',
      dataIndex: 'apiGroup',
      width: 150,
    },
    {
      title: 'API简介',
      dataIndex: 'description',
      width: 200,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 120,
      render: (_: any, record: SyncApiItem) => getMethodTag(record.method),
    },
  ];

  // 忽略API表格列
  const ignoreApiColumns = [
    {
      title: 'API路径',
      dataIndex: 'path',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'API分组',
      dataIndex: 'apiGroup',
      width: 150,
    },
    {
      title: 'API简介',
      dataIndex: 'description',
      width: 200,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 120,
      render: (_: any, record: SyncApiItem) => getMethodTag(record.method),
    },
    {
      title: '操作',
      width: 120,
      render: (_: any, record: SyncApiItem, index: number) => (
        <Button
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleIgnoreApi(record, index, false)}
        >
          取消忽略
        </Button>
      ),
    },
  ];

  return (
    <Drawer
      title="同步路由"
      width={900}
      open={visible}
      onClose={onClose}
      destroyOnClose
      extra={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleConfirmSync}>
            确定
          </Button>
        </Space>
      }
    >
      <WarningBar
        title="同步API，不输入路由分组将不会被自动同步，如果API不需要参与鉴权，可以按忽略按钮进行忽略。"
        type="warning"
      />

      <div style={{ marginTop: 24 }}>
        <Title level={5}>
          新增路由
          <Text type="secondary" style={{ fontSize: 12, marginLeft: 8, fontWeight: 'normal' }}>
            存在于当前路由中，但是不存在于API表
          </Text>
        </Title>
        <Table
          dataSource={newApis}
          columns={newApiColumns}
          rowKey={(record) => `${record.path}-${record.method}`}
          pagination={false}
          size="small"
          bordered
          locale={{ emptyText: '暂无新增路由' }}
        />
      </div>

      <div style={{ marginTop: 24 }}>
        <Title level={5}>
          已删除路由
          <Text type="secondary" style={{ fontSize: 12, marginLeft: 8, fontWeight: 'normal' }}>
            已经不存在于当前项目的路由中，确定同步后会自动从API表删除
          </Text>
        </Title>
        <Table
          dataSource={deleteApis}
          columns={deleteApiColumns}
          rowKey={(record) => `${record.path}-${record.method}`}
          pagination={false}
          size="small"
          bordered
          locale={{ emptyText: '暂无已删除路由' }}
        />
      </div>

      <div style={{ marginTop: 24 }}>
        <Title level={5}>
          忽略路由
          <Text type="secondary" style={{ fontSize: 12, marginLeft: 8, fontWeight: 'normal' }}>
            忽略路由不参与API同步，常见为不需要进行鉴权行为的路由
          </Text>
        </Title>
        <Table
          dataSource={ignoreApis}
          columns={ignoreApiColumns}
          rowKey={(record) => `${record.path}-${record.method}`}
          pagination={false}
          size="small"
          bordered
          locale={{ emptyText: '暂无忽略路由' }}
        />
      </div>
    </Drawer>
  );
};

export default ApiSync;
