import React from 'react';
import { Form, Input, Row, Col, Checkbox } from 'antd';
import {
  StateInfo,
  PointStateConfig,
  FileInfo,
  FileTypeEnum,
  ObjectPropsSyncChange,
} from '@easytwin/core';

import { LockIcon, BlurInput } from '@/components';
import { FileCard } from '@/pages/FileManage/components';

export interface PointFormProp {
  dataSource: StateInfo['config'];
  onChange: (data: PointStateConfig) => void;
}

type FormValuesChangeType = Omit<PointStateConfig, 'imgFileId'> & {
  imgFileId: FileInfo;
};

const PointForm: React.FC<PointFormProp> = function ({ dataSource, onChange }) {
  const [form] = Form.useForm();

  React.useEffect(() => {
    form.setFieldsValue(dataSource);
  }, [form, dataSource]);

  return (
    <Form
      form={form}
      className="!px-1"
      labelCol={{
        span: 6,
      }}
      wrapperCol={{
        span: 18,
      }}
      labelAlign="left"
      colon={false}
      onValuesChange={(changedValue: FormValuesChangeType) => {
        const { imgFileId } = changedValue;

        const newData: PointStateConfig = {
          ...(dataSource as PointStateConfig),
          ...changedValue,
          imgFileId: (dataSource as PointStateConfig).imgFileId,
        };

        if (imgFileId) {
          newData.imgFileId = imgFileId.id;
          newData.imgFileUrl = imgFileId.url;
        }

        onChange(
          ObjectPropsSyncChange(dataSource as PointStateConfig, newData, 'lockedSize', [
            'width',
            'height',
          ]),
        );
      }}>
      {/* 背景图 */}
      <Form.Item name="imgFileId" label="背景图" className="!mb-2">
        <FileCard
          mode={FileTypeEnum.IMAGE}
          changedValueType="info"
          innerContextClassName="p-2"
          showDeleteBtn={false}
        />
      </Form.Item>

      {/* 尺寸 */}
      <Form.Item label="尺寸" className="!mb-2">
        <Input.Group size="small">
          <Row gutter={8}>
            <Col span={10}>
              <Form.Item name="width" className="!mb-0">
                <BlurInput suffix="W" />
              </Form.Item>
            </Col>
            <Col span={10}>
              <Form.Item name="height" className="!mb-0">
                <BlurInput suffix="H" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="lockedSize" className="!mb-0">
                <LockIcon bordered className="!w-7 !h-7" />
              </Form.Item>
            </Col>
          </Row>
        </Input.Group>
      </Form.Item>

      {/* 顶层渲染  */}
      <Form.Item label="顶层渲染" name="alwaysTop" className="!mb-2" valuePropName="checked">
        <Checkbox />
      </Form.Item>
    </Form>
  );
};

export default PointForm;
