import { Container, Loading } from '@/components/shared'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Helmet } from 'react-helmet'
import { useParams } from 'react-router-dom'
import FormButtons from './FormButtons'
import FormDevExpress from './FormDevExpress'
import SubForms from './SubForms'
import { FormProps } from './types'
import { useGridData } from './useGridData'

const FormEdit = (
  props: FormProps = {
    isSubForm: false,
    onActionView: () => {},
    onActionNew: () => {},
  },
) => {
  const mode = 'edit'
  const { isSubForm, level } = props
  const params = useParams()
  const listFormCode = props?.listFormCode ?? params?.listFormCode ?? ''
  const id = props?.id ?? params?.id ?? ''

  // const refListFormCode = useRef('') //Şimdilik kalsın
  const { translate } = useLocalization()
  const {
    fetchData,
    setFormData,
    handleSubmit,
    loading,
    gridDto,
    dataSource,
    commandColumnData,
    filter,
    formData,
    formItems,
    refForm,
    permissionResults,
  } = useGridData({
    mode: 'edit',
    listFormCode,
    id,
    level,
    isSubForm,
    onSubmitAction: props?.onActionView,
  })

  if (!listFormCode) {
    return <></>
  }

  if (loading) {
    return <Loading type="cover" loading={loading}></Loading>
  }

  if (!formData) {
    return <>{translate('::Error:0002')}</>
  }

  return (
    <Container>
      {!isSubForm && (
        <Helmet
          titleTemplate="%s | Kurs Platform"
          title={translate('::' + gridDto?.gridOptions.title)}
          defaultTitle="Kurs Platform"
        ></Helmet>
      )}
      <div className="flex items-center justify-between mb-4">
        <h3>{translate('::App.Languages.Language')}</h3>
        {permissionResults && (
          <FormButtons
            mode={mode}
            listFormCode={listFormCode}
            id={formData?.Id}
            gridDto={gridDto!}
            commandColumnData={commandColumnData!}
            dataSource={dataSource!}
            permissions={permissionResults}
            handleSubmit={handleSubmit}
            refreshData={fetchData}
            getSelectedRowKeys={() => [id]}
            getSelectedRowsData={() => [formData]}
            getFilter={() => filter}
            onActionView={props?.onActionView}
            onActionNew={props?.onActionNew}
          />
        )}
      </div>
      <FormDevExpress
        mode={mode}
        refForm={refForm}
        formData={formData}
        formItems={formItems}
        setFormData={setFormData}
      />
      <hr className="my-4" />
      <SubForms gridDto={gridDto!} formData={formData} level={level ?? 0} />
    </Container>
  )
}

export default FormEdit
