import React, { useState, forwardRef, useImperativeHandle, useEffect } from 'react';
import { Form, Grid, Input, Message, Select } from '@arco-design/web-react';
import { submitEnvConfig } from '@/api/componentDeployEnv';

const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;

// 定义组件 Props 类型
interface FormEditorProps {
  record: any;
  envTypeOptions: { id: string | number; classifyType: string; classifyName: string, dictKey: string }[];
  setVisible: (visible: boolean) => void;
  onOk?: () => void;
  setConfirmLoading?: (loading: boolean) => void;
  onSuccess?: (value) => void;
}

// 定义暴露给父组件的实例类型
export interface FormEditorInstance {
  handleOk: () => void;
}

const FormEditor = forwardRef<FormEditorInstance, FormEditorProps>(({
                                                                      record,
                                                                      envTypeOptions,
                                                                      setConfirmLoading,
                                                                      onSuccess
                                                                    }, ref) => {
  const [form] = Form.useForm();

  // 暴露方法给父组件调用
  useImperativeHandle(ref, () => ({
    handleOk
  }));

  // 处理完成/确认逻辑
  const handleOk = async () => {
    try {
      const values = await form.validate();
      const params = {
        ...values,
        instanceCount: '',
        description: values.description ? values.description : ''
      };

      // 设置确认按钮为加载状态
      setConfirmLoading && setConfirmLoading(true);

      try {
        // 等待接口回调
        const res = await submitEnvConfig(params);
        Message.success('环境创建成功');

        // 如果有onSuccess回调，则调用它（用于切换步骤）
        if (onSuccess) {
          onSuccess(res.data);
        }
      } catch (error) {
        Message.error('环境创建失败: ' + error.message);
        // 保持模态框打开，让用户可以看到错误信息
      } finally {
        // 无论成功还是失败，都取消加载状态
        setConfirmLoading && setConfirmLoading(false);
      }
    } catch (error) {
      // 表单验证失败，不关闭模态框
      console.log('表单验证失败:', error);
      setConfirmLoading && setConfirmLoading(false);
    }
  };

  useEffect(() => {
    if (record) form.setFieldsValue(record);
    else form.resetFields();
  }, [record]);

  return (
    <Form form={form} layout="vertical">
      <Grid.Row gutter={8}>
        <Grid.Col span={12}>
          <FormItem label="环境IP：" field="ip" required rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请输入环境IP');
                }

                return cb();
              }
            }
          ]}>
            <Input style={{ width: '90%' }} allowClear placeholder="请输入环境IP" />
          </FormItem>
        </Grid.Col>
        <Grid.Col span={12}>
          <FormItem label="docker端口：" field="dockerTcpPort" required rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请输入docker端口');
                }

                return cb();
              }
            }
          ]}>
            <Input style={{ width: '90%' }} allowClear placeholder="请输入docker端口" />
          </FormItem>
        </Grid.Col>
      </Grid.Row>
      <Grid.Row gutter={8}>
        <Grid.Col span={12}>
          <FormItem label="环境类型：" field="type" required rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请选择环境类型');
                }

                return cb();
              }
            }
          ]}>
            <Select
              placeholder="请选择环境类型"
              style={{ width: '90%' }}
            >
              {envTypeOptions.map((option, index) => (
                <Option key={option.id} value={option.dictKey}>
                  {option.classifyName}
                </Option>
              ))}
            </Select>
          </FormItem>
        </Grid.Col>
        <Grid.Col span={12}>
          <FormItem label="架构类型：" field="arch" required rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请选择架构类型');
                }

                return cb();
              }
            }
          ]}>
            <Select
              placeholder="请选择架构类型"
              style={{ width: '90%' }}
            >
              {['x86_64', 'aarch64'].map((option, index) => (
                <Option key={option} disabled={index === 3} value={option}>
                  {option}
                </Option>
              ))}
            </Select>
          </FormItem>
        </Grid.Col>
      </Grid.Row>
      <Grid.Row gutter={8}>
        <Grid.Col span={12}>
          <FormItem label="环境别名：" field="name" required rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请输入环境别名');
                }

                return cb();
              }
            }
          ]}>
            <Input style={{ width: '90%' }} allowClear placeholder="请输入环境别名" />
          </FormItem>
        </Grid.Col>
        <Grid.Col span={12}>
          <FormItem label="备注：" field="description">
            <TextArea style={{ width: '90%' }} allowClear placeholder="请输入备注" />
          </FormItem>
        </Grid.Col>
      </Grid.Row>
    </Form>

  );
});

export default FormEditor;