import React, { memo, useEffect, useCallback, useState } from 'react';
import { Form, Input, Switch } from '@easyv/antd';
import ConfirmModal from 'components/ConfirmModal';
import UploadThumb from 'components/UploadThumb';
import defaultThumb from 'images/default.png';
import {getAssetsUrl} from 'utils/utils';

function EditModal({
  visible = false,
  confirmLoading,
  id,
  name,
  thumb,
  isDefault = false,
  published = true,
  isCover = true,
  coverShow,
  onCancel,
  onOk
}: {
  visible?: boolean;
  confirmLoading?: boolean;
  id?: number;
  name?: string;
  thumb?: string;
  isDefault?: boolean;
  published?: boolean;
  isCover?: boolean;
  coverShow?: boolean;
  onCancel: () => any;
  onOk: (param) => any;
}) {
  const [form] = Form.useForm();
  const [_thumb, setThumb] = useState<string | File>('');
  const { validateFields } = form;

  useEffect(() => {
    setThumb(thumb || '');
  }, [thumb]);

  const handleSubmit = useCallback(() => {
    validateFields().then((values) => {
      onOk({
        ...values,
        thumb: _thumb
      });
    });
  }, [_thumb]);

  const handleThumbChange = useCallback((file) => {
    setThumb(file);
  }, []);

  return (
    <ConfirmModal
      visible={visible}
      title={id ? '编辑主题信息' : '保存主题配置信息'}
      footer={true}
      okText="保存"
      confirmLoading={confirmLoading}
      destroyOnClose
      onCancel={onCancel}
      onOk={handleSubmit}>
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
        autoComplete="off"
        initialValues={{ name, isDefault, published, isCover }}>
        <Form.Item
          label="主题名称"
          name="name"
          rules={[
            { required: true, whitespace: true, message: '主题名称必填' },
            { max: 12, message: '不要超过12个字符' }
          ]}>
          <Input placeholder="请输入主题名称，12字符以内" />
        </Form.Item>

        <Form.Item label="缩略图" name="thumb">
          <UploadThumb url={_thumb ? getAssetsUrl(`${_thumb}`) : defaultThumb} onChange={handleThumbChange} />
        </Form.Item>

        <Form.Item label="设为默认主题" name="isDefault" valuePropName="checked" style={{ marginBottom: 0 }}>
          <Switch />
        </Form.Item>

        <Form.Item label="上架状态" name="published" valuePropName="checked" style={{ marginBottom: 0 }}>
          <Switch />
        </Form.Item>

        {coverShow && (
          <Form.Item label="覆盖当前主题" name="isCover" valuePropName="checked">
            <Switch />
          </Form.Item>
        )}
      </Form>
    </ConfirmModal>
  );
}

export default memo(EditModal);
