import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Space,
  Button,
  Message
} from '@arco-design/web-react';
import { getComponentClassify } from '@/api/componentClassify';
import { copyDesign } from '@/api/componentMarket';
import { copyAll } from '@/api/componentBase';
import EditorSection from '@/components/EditorSection';

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

interface CopyComponentModalProps {
  visible: boolean;
  componentInfo: any;
  onCancel: () => void;
  onSuccess?: () => void;
}

const CopyComponentModal: React.FC<CopyComponentModalProps> = ({
                                                                 visible,
                                                                 componentInfo,
                                                                 onCancel,
                                                                 onSuccess
                                                               }) => {
  const [form] = Form.useForm();
  const [classifyList, setClassifyList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [description, setDescription] = useState('');

  // 组件语言选项
  const codeLanguageOptions = [
    { label: 'Java:8', value: 'Java' },
    { label: 'Python:3.10.12', value: 'Python' }
  ];

  // 组件类型选项
  const componentTypeOptions = [
    { label: '普通组件', value: 'normal' },
    { label: '监听组件', value: 'loop' }
  ];

  // 获取组件分类列表
  const getComponentClassifyList = async () => {
    try {
      const res: any = await getComponentClassify('component');
      if (res.code === 200) {
        const data = res.data.map((item) => ({
          label: item.classifyName,
          value: item.id
        }));
        setClassifyList(data);
      }
    } catch (error) {
      console.error('获取组件分类失败:', error);
    }
  };

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

  // 当弹窗打开时，设置表单初始值
  useEffect(() => {
    if (visible && componentInfo) {
      form.setFieldsValue({
        name: componentInfo.name || '',
        projectId: '', // 复制时项目标识需要重新填写
        componentClassify: componentInfo.componentClassify || '',
        codeLanguage: componentInfo.codeLanguage || '',
        type: componentInfo.type || 'normal'
      });
      setDescription(componentInfo.desc || '');
    }
  }, [visible, componentInfo, form]);

  // 仅复制设计
  const handleCopyDesign = async () => {
    try {
      await form.validate();
      const formData = form.getFields();

      setLoading(true);
      const params = {
        id: componentInfo.id,
        name: formData.name,
        projectId: formData.projectId,
        componentClassify: formData.componentClassify,
        codeLanguage: formData.codeLanguage,
        type: formData.type,
        desc: description
      };

      const res: any = await copyDesign(params);

      if (res.code === 200) {
        Message.success('仅复制设计成功');
        onSuccess?.();
        handleClose();
      }
      else {
        Message.error(res.message || '复制失败');
      }
    } catch (error) {
      console.error('复制失败:', error);
      Message.error('复制失败');
    } finally {
      setLoading(false);
    }
  };

  // 复制设计和代码
  const handleCopyAll = async () => {
    try {
      await form.validate();
      const formData = form.getFields();

      setLoading(true);
      const params = {
        id: componentInfo.id,
        name: formData.name,
        projectId: formData.projectId,
        componentClassify: formData.componentClassify,
        codeLanguage: formData.codeLanguage,
        type: formData.type,
        desc: description
      };

      const res: any = await copyAll(params);

      if (res.code === 200) {
        Message.success('复制设计和代码成功');
        onSuccess?.();
        handleClose();
      }
      else {
        Message.error(res.message || '复制失败');
      }
    } catch (error) {
      console.error('复制失败:', error);
      Message.error('复制失败');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title="复制组件到我的组件"
      visible={visible}
      onCancel={handleClose}
      footer={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button
            type="primary"
            onClick={handleCopyDesign}
            loading={loading}
          >
            仅复制设计
          </Button>
          <Button
            type="primary"
            status="success"
            onClick={handleCopyAll}
            loading={loading}
          >
            复制设计和代码
          </Button>
        </Space>
      }
      style={{ width: '70%', maxWidth: 900 }}
    >
      <Form
        form={form}
        layout="vertical"
        autoComplete="off"
      >
        <FormItem
          label="组件名称"
          field="name"
          rules={[{ required: true, message: '请输入组件名称' }]}
        >
          <Input placeholder="请输入组件名称" />
        </FormItem>

        <FormItem
          label="组件标识"
          field="projectId"
          rules={[
            { required: true, message: '请输入组件标识' },
            {
              validator: (value, callback) => {
                if (value && !/^[a-zA-Z][a-zA-Z0-9_]*$/.test(value)) {
                  callback('组件标识必须以字母开头，只能包含字母、数字和下划线');
                }
                else {
                  callback();
                }
              }
            }
          ]}
        >
          <Input placeholder="请输入组件标识，如：my_component" />
        </FormItem>

        <FormItem
          label="组件分类"
          field="componentClassify"
          rules={[{ required: true, message: '请选择组件分类' }]}
        >
          <Select placeholder="请选择组件分类">
            {classifyList.map((item) => (
              <Option key={item.value} value={item.label}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>

        <FormItem
          label="代码语言"
          field="codeLanguage"
          rules={[{ required: true, message: '请选择代码语言' }]}
        >
          <Select placeholder="请选择代码语言" disabled>
            {codeLanguageOptions.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>

        <FormItem
          label="组件类型"
          field="type"
          rules={[{ required: true, message: '请选择组件类型' }]}
        >
          <Select placeholder="请选择组件类型">
            {componentTypeOptions.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>

        <FormItem label="描述">
          <EditorSection
            visible={visible}
            initialContent={description}
          />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default CopyComponentModal;
