import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Checkbox, Message } from '@arco-design/web-react';
import Cover from '@/pages/scene/cover';
import ConfigTable from '@/pages/scene/configTable';
import { addScene, editScene } from '@/api/scene';

const FormItem = Form.Item;

interface OperationModalProps {
  show: boolean;
  type: string;
  item: any;
  onClose: (status: boolean) => void;
  onRefresh: () => void;
}

const OperationModal: React.FC<OperationModalProps> = ({ show, type, item, onClose, onRefresh }) => {
  const [visible, setVisible] = useState(false);
  const [selectedImage, setSelectedImage] = useState('');
  const [configUrls, setConfigUrls] = useState([]);
  const [form] = Form.useForm();


  const transformImageUrl = (image: string) => {
    if (!image) return;
    if (image.includes('/')) setSelectedImage(image.split('/')[image.split('/').length - 1]);
    else setSelectedImage(image);
  };

  const onOk = async () => {
    await form.validate();
    const formData = form.getFields();

    const params = {
      ...formData,
      logo: selectedImage,
      published: formData.published ? 1 : 0,
      configUrls: configUrls
    };
    if (type === 'ADD') {
      const res: any = await addScene(params);
      if (res.code === 200) {
        Message.success('创建成功');
        setVisible(false);
        onClose(false);
        onRefresh();
        // 清空表单数据和其他变量数据
        form.resetFields();
        setSelectedImage('');
        setConfigUrls([]);
      }
    }
    else {
      const res: any = await editScene(params);
      if (res.code === 200) {
        Message.success('更新成功');
        setVisible(false);
        onClose(false);
        onRefresh();
        // 清空表单数据和其他变量数据
        form.resetFields();
        setSelectedImage('');
        setConfigUrls([]);
      }
    }
  };

  useEffect(() => {
    setVisible(show);
  }, [show]);

  useEffect(() => {
    transformImageUrl(item?.logo);
    form.setFieldsValue({
      id: item?.id,
      name: item?.name,
      description: item?.description,
      published: item?.published === 1
    });
    setConfigUrls(item?.configUrls || []);
  }, [item]);

  return (
    <Modal
      style={{ width: '50%' }}
      title={type === 'ADD' ? '创建工程' : '编辑工程'}
      visible={visible}
      onOk={() => onOk()}
      onCancel={() => onClose(false)}
      autoFocus={false}
      focusLock={true}
    >
      <Form form={form} autoComplete="off">
        <FormItem label="封面图">
          <Cover
            defaultImage={item?.logo}
            onImageChange={(selectedImage) => transformImageUrl(selectedImage)}
          />
        </FormItem>
        <FormItem
          field="name"
          label="名称"
          required
          rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请填写工程名称');
                }
                // 检查是否只包含汉字
                const chineseOnlyRegex = /^[\u4e00-\u9fa5]+$/;
                if (!chineseOnlyRegex.test(value)) {
                  return cb('工程名称只能输入汉字');
                }

                return cb();
              }
            }
          ]}
        >
          <Input placeholder="请输入工程名称" />
        </FormItem>
        <FormItem
          field="description"
          label="描述"
          required
          rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请填写工程描述');
                }

                return cb();
              }
            }
          ]}
        >
          <Input placeholder="请输入工程描述" />
        </FormItem>
        <FormItem field="configUrls" label="大屏">
          <ConfigTable
            configUrls={configUrls}
            onChange={(data) => setConfigUrls(data)}
          />
        </FormItem>
        <FormItem field="published" label=" ">
          <Checkbox>是否公开</Checkbox>
        </FormItem>
      </Form>
    </Modal>
  );
};

export default OperationModal;