/**
 * KRA - API Form Drawer Component
 * Create and edit API
 */
import React, { useState, useEffect } from 'react';
import { Drawer, Form, Input, Select, Button, Space, message } from 'antd';
import { createApi, updateApi } from '@/services/kratos/api';
import WarningBar from '@/components/WarningBar/WarningBar';
import type { ApiItem } from '../index';

interface ApiFormProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  initialValues: ApiItem | null;
  dialogFlag: 'add' | 'edit';
  apiGroupOptions: { label: string; value: string }[];
}

const methodOptions = [
  { value: 'POST', label: '创建(POST)' },
  { value: 'GET', label: '查看(GET)' },
  { value: 'PUT', label: '更新(PUT)' },
  { value: 'DELETE', label: '删除(DELETE)' },
];

const ApiForm: React.FC<ApiFormProps> = ({
  visible,
  onClose,
  onSuccess,
  initialValues,
  dialogFlag,
  apiGroupOptions,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 初始化表单
  useEffect(() => {
    if (visible) {
      if (dialogFlag === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
      }
    }
  }, [visible, initialValues, dialogFlag, form]);

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      let res;
      if (dialogFlag === 'edit' && initialValues) {
        res = await updateApi({ ...initialValues, ...values });
      } else {
        res = await createApi(values);
      }

      if (res.code === 0) {
        message.success(dialogFlag === 'edit' ? '编辑成功' : '添加成功');
        onSuccess();
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title={dialogFlag === 'edit' ? '编辑API' : '新增API'}
      width={500}
      open={visible}
      onClose={onClose}
      destroyOnClose
      extra={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
    >
      <WarningBar title="新增API，需要在角色管理内配置权限才可使用" type="warning" />
      <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
        <Form.Item
          name="path"
          label="路径"
          rules={[{ required: true, message: '请输入API路径' }]}
        >
          <Input placeholder="请输入API路径" />
        </Form.Item>

        <Form.Item
          name="method"
          label="请求方法"
          rules={[{ required: true, message: '请选择请求方法' }]}
        >
          <Select placeholder="请选择请求方法" options={methodOptions} />
        </Form.Item>

        <Form.Item
          name="apiGroup"
          label="API分组"
          rules={[{ required: true, message: '请选择或输入API分组' }]}
        >
          <Select
            placeholder="请选择或新增"
            options={apiGroupOptions}
            showSearch
            allowClear
            mode="tags"
            maxCount={1}
          />
        </Form.Item>

        <Form.Item
          name="description"
          label="API简介"
          rules={[{ required: true, message: '请输入API简介' }]}
        >
          <Input placeholder="请输入API简介" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default ApiForm;
