import {memo, useCallback, 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 DomainForm = memo(({
  open,
  values,
  onCancel,
  onFinish
}) => {

  const t = useI18NPrefix('global');
  const domains = useAppSelector(selectDomains);
  const formRef = useRef();

  const submitter = {
    submitButtonProps: {
      style:{
        marginLeft:20,
        marginTop:20
      }
    },
    resetButtonProps: {
      style:{
        marginTop:20,
        marginLeft:'45%'
      }
    }
  }

  const onHandleSubmit = useCallback((v) => {
    onFinish && onFinish({
      ...v,
      id:values?.id,
    })
  },[values])
  return (
    <CustomModal
      width={800}
      title={<Title children={`${t(values?.id?"button.edit":"button.create")}${t("title.domain")}`}/>}
      open={open}
      footer={null}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
    >
      <ProForm
        formRef={formRef}
        layout={formLayoutType}
        onFinish={onHandleSubmit}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 17 }}
        submitter={submitter}
        initialValues={values}
      >
        <ProFormTreeSelect
          name="parentId"
          label={t("formItem.parentDomain")}
          request={async ()=>domains}
          initialValue={values?.pId===0 ? null : values?.pId}
        />
        <ProFormText
          name="name"
          label={t("formItem.domain")+t("formItem.name")}
          rules={[{ required: true }]}
          initialValue={values?.name}
        />
        <ProFormText
          name="description"
          label={t("formItem.description")}
          initialValue={values?.description}
        />
        <ProFormDatePicker name="startDate" label={t("formItem.startDate")} rules={[{ required: true }]} width="100%" initialValue={values?.createdAt}/>
        <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;
  }
`
