import React, { useState, useEffect, useCallback } from 'react';
import { NodeEditorProps } from '@/components/FlowEditor/nodeEditors';
import { Typography, Form, Grid, Select, Input, Button, Link, Message } from '@arco-design/web-react';
import { IconUnorderedList } from '@arco-design/web-react/icon';
import ParamsTable from './ParamsTable';
import KYTable from '@/components/FlowEditor/nodeEditors/components/KYTable';
import CodeMirror from '@uiw/react-codemirror';
import { json } from '@codemirror/lang-json';

const Row = Grid.Row;
const Col = Grid.Col;

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

const RestEditor: React.FC<NodeEditorProps & {
  onValidationChange?: (isValid: boolean) => void
}> = ({ nodeData, updateNodeData, onValidationChange }) => {
  const [formData, setFormData] = useState({
    method: 'GET',
    url: '',
    inputType: 'JSON',
    headers: [],
    defaultInput: '',
    dataIns: nodeData.parameters.dataIns || [],
    component: {}
  });

  const [isShowHeaders, setIsShowHeaders] = useState(false);
  const [isShowDataIns, setIsShowDataIns] = useState(false);
  const [isValidUrl, setIsValidUrl] = useState(true); // 添加URL有效性状态
  const [value, setValue] = useState('');

  const methodList = ['GET', 'POST'];
  const dataTypeList = [
    { label: 'JSON', value: 'JSON' },
    { label: '路径参数', value: '路径参数' }
  ];

  // URL 校验函数
  const validateUrl = useCallback((url: string) => {
    if (!url) return true; // 空URL认为是有效的（但会在提交时提示）

    // 基本的 URL 格式校验正则表达式
    const urlPattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    return urlPattern.test(url);
  }, []);

  // 通知父组件校验状态变化
  useEffect(() => {
    if (onValidationChange) {
      onValidationChange(isValidUrl);
    }
  }, [isValidUrl, onValidationChange]);

  // 初始化数据
  useEffect(() => {
    if (nodeData.component && nodeData.component.customDef) {
      try {
        const customDef = typeof nodeData.component.customDef === 'string'
          ? JSON.parse(nodeData.component.customDef)
          : nodeData.component.customDef;

        setFormData(prev => ({
          ...prev,
          method: customDef.method || 'GET',
          url: customDef.url || '',
          inputType: customDef.inputType || 'JSON',
          headers: customDef.headers || [],
          defaultInput: customDef.defaultInput || '',
          dataIns: nodeData.parameters.dataIns || []
        }));

        // 检查初始URL有效性
        const initialUrlValid = validateUrl(customDef.url || '');
        setIsValidUrl(initialUrlValid);

        setIsShowHeaders(!!(customDef.headers && customDef.headers.length > 0));
        setIsShowDataIns(!!(nodeData.parameters.dataIns && nodeData.parameters.dataIns.length > 0));
      } catch (e) {
        console.error('解析组件数据失败:', e);
      }
    }
  }, [nodeData, validateUrl]);

  // 更新表单数据时同步到节点
  const handleFormChange = (newFormData) => {
    setFormData(newFormData);

    // 更新 component 数据
    const componentData = {
      ...nodeData.component,
      customDef: JSON.stringify({
        method: newFormData.method,
        url: newFormData.url,
        inputType: newFormData.inputType,
        headers: newFormData.headers,
        defaultInput: newFormData.defaultInput
      }),
      type: 'REST'
    };

    updateNodeData('component', componentData);
  };

  const handleChangeMethod = (method) => {
    handleFormChange({ ...formData, method });
  };

  const handleUrlChange = (url) => {
    // 实时校验URL
    const isValid = validateUrl(url);
    setIsValidUrl(isValid);

    handleFormChange({ ...formData, url });

    // 可选：在用户输入时实时校验 URL
    if (url && !isValid) {
      // 这里可以添加实时提示，但不阻止用户输入
      console.warn('URL 格式可能不正确');
    }
  };

  const formatJSON = () => {
    try {
      console.log('formData.defaultInput:', formData.defaultInput);
      const formatted = JSON.stringify(JSON.parse(formData.defaultInput), null, 2);
      handleFormChange({ ...formData, defaultInput: formatted });
    } catch (e) {
      // 如果不是有效的JSON，不进行格式化
      Message.error('无效的 JSON 格式');
    }
  };

  // URL 校验并提示
  const handleUrlBlur = () => {
    if (formData.url && !validateUrl(formData.url)) {
      Message.warning('请输入有效的 URL 地址');
    }
  };

  return (
    <>
      <Form layout="vertical">
        <div style={{ padding: '0 16px' }}>
          <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />请求方法</Typography.Title>
          <Row gutter={10}>
            <Col span={6}>
              <FormItem label="方法:" required>
                <Select
                  value={formData.method}
                  onChange={handleChangeMethod}
                >
                  {methodList.map(method => (
                    <Option key={method} value={method}>
                      {method}
                    </Option>
                  ))}
                </Select>
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="URL地址:" required validateStatus={formData.url && !isValidUrl ? 'error' : 'success'}>
                <Input
                  value={formData.url}
                  onChange={handleUrlChange}
                  onBlur={handleUrlBlur}
                  placeholder="请输入URL地址，例如: https://api.example.com/endpoint"
                />
                {formData.url && !isValidUrl && (
                  <div style={{ color: '#ff0000', fontSize: '12px', marginTop: '4px' }}>
                    请输入有效的 URL 地址
                  </div>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem label="参数类型:">
                <Select
                  value={formData.inputType}
                  onChange={inputType => handleFormChange({ ...formData, inputType })}
                >
                  {dataTypeList.map(item => (
                    <Option key={item.value} value={item.value}>
                      {item.label}
                    </Option>
                  ))}
                </Select>
              </FormItem>
            </Col>
          </Row>
        </div>

        <div style={{ padding: '0 16px' }}>
          <Row gutter={24}>
            <Col span={24}>
              <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />请求头
                {!isShowHeaders ? (
                  <Link onClick={() => setIsShowHeaders(true)} style={{ marginLeft: 8 }}>
                    配置
                  </Link>
                ) : null}
              </Typography.Title>
              <FormItem>
                {isShowHeaders ? (
                  <div>
                    {/* 这里需要实现KV编辑器，暂时用简单输入框替代 */}
                    <KYTable
                      initialData={formData.headers}
                      onChange={(data) => {
                        handleFormChange({ ...formData, headers: data });
                      }} />
                  </div>
                ) : null}
              </FormItem>
            </Col>

            <Col span={24}>
              <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />
                请求报文
                <Link onClick={formatJSON} style={{ marginLeft: 8 }}>
                  格式化
                </Link>
              </Typography.Title>
              <FormItem>
                <CodeMirror
                  value={value}
                  height="300px"
                  extensions={[json()]}
                  onChange={data => {
                    setValue(data);
                    handleFormChange({ ...formData, defaultInput: data });
                  }} />
              </FormItem>
            </Col>

            <Col span={24}>
              <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />
                输入参数
                {!isShowDataIns ? (
                  <Link onClick={() => setIsShowDataIns(true)} style={{ marginLeft: 8 }}>
                    配置
                  </Link>
                ) : null}
              </Typography.Title>
              <FormItem>
                {isShowDataIns ? (
                  <div>
                    <ParamsTable
                      initialData={formData.dataIns}
                      onUpdateData={(dataIns) => {
                        handleFormChange({ ...formData, dataIns });
                        // 同时更新parameters.dataIns
                        updateNodeData('parameters', {
                          ...nodeData.parameters,
                          dataIns
                        });
                      }}
                    />
                  </div>
                ) : null}
              </FormItem>
            </Col>
          </Row>
        </div>
      </Form>
    </>
  );
};

export default RestEditor;