import { Container, Loading } from '@/components/shared'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { DataType } from 'devextreme/common'
import { SimpleItem } from 'devextreme/ui/form'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import { useParams, useSearchParams } from 'react-router-dom'
import FormButtons from './FormButtons'
import FormDevExpress from './FormDevExpress'
import { FormProps } from './types'
import { useGridData } from './useGridData'

const FormNew = (
  props: FormProps = {
    isSubForm: false,
  },
) => {
  const mode = 'new'
  const { isSubForm, level, sParams } = props
  const params = useParams()
  const listFormCode = props?.listFormCode ?? params?.listFormCode ?? ''
  const [searchParams] = useSearchParams()
  // const refListFormCode = useRef('') //Şimdilik kalsın
  const { translate } = useLocalization()
  const {
    setFormData,
    loading,
    handleSubmit,
    gridDto,
    dataSource,
    commandColumnData,
    formData,
    formItems,
    refForm,
    permissionResults,
  } = useGridData({
    mode,
    listFormCode,
    level,
    isSubForm,
    onSubmitAction: props?.onActionView,
  })
  const [newParams, setNewParams] = useState<URLSearchParams>(new URLSearchParams())

  useEffect(() => {
    setNewParams(
      new URLSearchParams({
        ...Object.fromEntries(searchParams),
        ...Object.fromEntries(sParams ?? []),
      }),
    )
  }, [searchParams, sParams])

  useEffect(() => {
    if (!formItems) {
      return
    }

    setFormData(createInitialFormData())
  }, [formItems, newParams])

  function createInitialFormData() {
    const data: any = {}
    if (!formItems?.length) {
      return data
    }

    // Default tüm alanlar undefined olsun
    for (const formGroupItem of formItems) {
      if (formGroupItem.items) {
        //SimpleItem
        for (const formItem of formGroupItem.items) {
          const f = formItem as SimpleItem
          data[f.dataField!] = undefined
        }
      }
    }

    if (!gridDto?.columnFormats) {
      return
    }
    for (const colFormat of gridDto?.columnFormats) {
      if (!colFormat.fieldName) {
        continue
      }

      // Grid'den gelen columnFormat'ları kullanarak default değerleri set et
      if (colFormat.defaultValue != null) {
        data[colFormat.fieldName] = colFormat.defaultValue
      }

      // URL'den veya Component Prop'dan gelen parametreleri set et
      if (newParams.has(colFormat.fieldName)) {
        const dType = colFormat.dataType as DataType
        switch (dType) {
          case 'date':
          case 'datetime':
            data[colFormat.fieldName] = new Date(newParams.get(colFormat.fieldName)!)
            break
          case 'number':
            data[colFormat.fieldName] = Number(newParams.get(colFormat.fieldName))
            break
          case 'boolean':
            if (newParams.get(colFormat.fieldName) === 'true') {
              data[colFormat.fieldName] = true
            } else if (newParams.get(colFormat.fieldName) === 'false') {
              data[colFormat.fieldName] = false
            }
            break
          case 'object':
            try {
              data[colFormat.fieldName] = JSON.parse(newParams.get(colFormat.fieldName) as string)
            } catch (error) {}
            break
          default:
            data[colFormat.fieldName] = newParams.get(colFormat.fieldName)
            break
        }

        // Eğer default value varsa, bu editörü readonly yapıyoruz
        formItems.forEach((form) => {
          form?.items?.forEach((item: SimpleItem) => {
            if (item.dataField === colFormat.fieldName) {
              item.editorOptions = { ...item.editorOptions, readOnly: true }
            }
          })
        })
      }
    }

    return data
  }

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

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

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

  return (
    <Container>
      {!isSubForm && (
        <Helmet
          titleTemplate="%s | Sözsoft Kurs Platform"
          title={translate('::' + gridDto?.gridOptions.title)}
          defaultTitle="Sözsoft Kurs Platform"
        ></Helmet>
      )}
      <div
        className={`flex items-center pb-2 px-2 ${isSubForm ? 'justify-end' : 'justify-between'}`}
      >
        {!isSubForm && <h3>{translate('::' + gridDto?.gridOptions.title)}</h3>}
        {permissionResults && (
          <FormButtons
            isSubForm={isSubForm}
            mode={mode}
            listFormCode={listFormCode}
            id={formData?.Id}
            gridDto={gridDto!}
            commandColumnData={commandColumnData!}
            dataSource={dataSource!}
            permissions={permissionResults}
            handleSubmit={handleSubmit}
            refreshData={() => {}}
            getSelectedRowKeys={() => []}
            getSelectedRowsData={() => [formData]}
            getFilter={() => []}
            onActionView={props?.onActionView}
          />
        )}
      </div>
      <div className="px-2">
        <FormDevExpress
          mode={mode}
          refForm={refForm}
          formData={formData}
          formItems={formItems}
          setFormData={setFormData}
          listFormCode={listFormCode}
        />
      </div>
    </Container>
  )
}

export default FormNew
