import React from 'react';
import { Input, Row, Col, Form, Checkbox } from 'antd';

import { StateInfo, ProjectStateConfig, FileInfo, FileTypeEnum } from '@easytwin/core';
import { SliderInput, ColorInput } from '@/components';
import { FileCard } from '@/pages/FileManage/components';

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

type FormValuesChangeType = Omit<ProjectStateConfig, 'hdrFileId'> & {
  hdrFileId?: FileInfo;
};

const ProjectForm: React.FC<ProjectFormProp> = 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 { hdrFileId } = changedValue;

        const newData: ProjectStateConfig = {
          ...(dataSource as ProjectStateConfig),
          ...changedValue,
          hdrFileId: (dataSource as ProjectStateConfig).hdrFileId,
        };

        if (hdrFileId) {
          newData.hdrFileId = hdrFileId.id;
          newData.hdrFileUrl = hdrFileId.url;
        }

        onChange(newData);
      }}>
      {/* 天光颜色 */}
      <Form.Item name="ambientLightColor" label="天光颜色" className="!mb-2">
        <ColorInput />
      </Form.Item>

      {/* 天光强度 */}
      <Form.Item name="ambientLightIntensity" label="天光强度" className="!mb-2">
        <SliderInput min={0.1} max={2} step={0.1} />
      </Form.Item>

      {/* 场景背景 */}
      <Form.Item label="场景背景" className="!mb-2">
        <Input.Group size="small">
          <Row gutter={8}>
            <Col span={15}>
              <Form.Item name="backgroundColor" className="!mb-0">
                <ColorInput />
              </Form.Item>
            </Col>
            <Col span={9}>
              <Form.Item name="backgroundOpacity" className="!mb-0">
                <Input size="small" className="!w-full" suffix="%" />
              </Form.Item>
            </Col>
          </Row>
        </Input.Group>
      </Form.Item>

      {/* useHdr */}
      <Form.Item name="useHdr" label="环境贴图" className="!mb-2" valuePropName="checked">
        <Checkbox />
      </Form.Item>

      {/* hdrFileId */}
      {(dataSource as ProjectStateConfig)?.useHdr && (
        <Form.Item name="hdrFileId" label=" " className="!mb-2">
          <FileCard
            mode={FileTypeEnum.FILE}
            uploadAccept=".hdr"
            changedValueType="info"
            onRemove={() =>
              onChange({
                ...(dataSource as ProjectStateConfig),
                hdrFileId: null,
                hdrFileUrl: null,
              })
            }
          />
        </Form.Item>
      )}
    </Form>
  );
};

export default ProjectForm;
