import {memo, useEffect, useRef} from 'react';
import {Modal} from 'antd';
import {ProForm, ProFormDatePicker, ProFormText, ProFormTreeSelect} from '@ant-design/pro-components';
import {styled} from 'styled-components'
import {useAppSelector} from "../../../../redux/configureStore";
import {selectDomains} from "../../MainPage/slice/selectors";
import useI18NPrefix from "../../../hooks/useI18NPrefix";

const formLayoutType = "horizontal";

export const DatasetForm = memo(({
  open,
  data,
  onCancel,
  onFinish,
  initialValues
}) => {
  const t = useI18NPrefix('global');
  const domains = useAppSelector(selectDomains);
  const formRef = useRef();

  useEffect(() => {
    formRef?.current?.setFieldsValue(data);
  }, [data])

  const handleSubmit = (values) => {
    onFinish({
      id:initialValues?.id,
      ...values
    })
  }

  const submitter = {
    submitButtonProps: {
      style: {
        marginLeft: 20,
        marginTop: 20
      }
    },
    resetButtonProps: {
      style: {
        marginTop: 20,
        marginLeft: '40%'
      }
    }
  }
  return (
    <CustomModal
      width={800}
      title={<Title children={t("title.datasetCreate")} />}
      open={open}
      footer={null}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
    >
      <ProForm
        formRef={formRef}
        layout={formLayoutType}
        onFinish={handleSubmit}
        labelCol={{span: 4}}
        wrapperCol={{span: 18}}
        submitter={submitter}
        initialValues={initialValues}
      >
        <ProFormTreeSelect
          name="domainId"
          label={t("formItem.domain")}
          rules={[{required: true}]}
          request={async () => domains}
        />
        <ProFormText
          name="name"
          label={t("formItem.datasetName")}
          rules={[{required: true}]}
        />
        <ProFormText
          name="bizName"
          label={t("formItem.bizName")}
          rules={[{required: true}]}
        />
        <ProFormText
          name="description"
          label={t("formItem.description")}
        />
        <ProFormDatePicker name="startDate" label={t("formItem.startDate")} width="100%"/>
        <ProFormDatePicker name="stopDate" label={t("formItem.stopDate")} width="100%"/>
      </ProForm>
    </CustomModal>
  )
})

const Title = styled.div`
    margin-left: 24px;
`

const CustomModal = styled(Modal)`
    .ant-modal-content {
        padding: 24px 0;
    }
`
