import { DX_CLASSNAMES } from '@/constants/app.constant'
import {
  Form as FormDx,
  GroupItem as GroupItemDx,
  Label as LabelDx,
  SimpleItem as SimpleItemDx,
} from 'devextreme-react/form'
import { FieldDataChangedEvent, GroupItem } from 'devextreme/ui/form'
import { Dispatch, RefObject, useEffect, useRef } from 'react'
import { GridBoxEditorComponent } from './editors/GridBoxEditorComponent'
import { TagBoxEditorComponent } from './editors/TagBoxEditorComponent'
import { RowMode, SimpleItemWithColData } from './types'
import { PlatformEditorTypes } from '@/proxy/form/models'
import dxSelectBox from 'devextreme/ui/select_box'

const FormDevExpress = (props: {
  listFormCode: string
  isSubForm?: boolean
  mode: RowMode
  refForm: RefObject<FormDx>
  formData: any
  formItems: GroupItem[]
  setFormData: Dispatch<any>
}) => {
  const { listFormCode, isSubForm, mode, refForm, formData, formItems, setFormData } = props

  const formDataRef = useRef(formData)
  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  return (
    <form className={`${DX_CLASSNAMES} ${!isSubForm ? 'px-2' : ''} pb-2`}>
      <FormDx
        ref={refForm}
        formData={formData}
        onFieldDataChanged={async (e: FieldDataChangedEvent) => {
          setFormData({ ...formData, [e.dataField!]: e.value })

          //Dinamik script
          const changeItem = formItems
            .flatMap((group) => (group.items as SimpleItemWithColData[]) || [])
            .find((i: SimpleItemWithColData) => i.dataField === e.dataField)

          if (changeItem?.script) {
            try {
              //setFormData({...formData, Path: e.value});
              //UiEvalService.ApiGenerateBackgroundWorkers();
              //setFormData({ ...formData, Path: (v => v === '1' ? '1-deneme' : v === '0' ? '0-deneme' : '')(e.value) })
              eval(changeItem.script)
            } catch (err) {
              console.error('Script execution failed for', changeItem.name, err)
            }
          }
        }}
        onContentReady={(e) => {
          const groupItems = e.component.option('items') as any[]
          const firstItem = groupItems?.[0]?.items?.[0]

          if (firstItem?.dataField) {
            const editor = e.component.getEditor(firstItem.dataField)
            mode !== 'view' && editor?.focus()
          }
        }}
      >
        {formItems.map((formGroupItem, i) => {
          return (
            <GroupItemDx
              key={'formGroupItem-' + i}
              colCount={formGroupItem.colCount}
              colSpan={formGroupItem.colSpan}
              caption={formGroupItem.caption}
            >
              {(formGroupItem.items as SimpleItemWithColData[])?.map((formItem, i) => {
                return formItem.editorType2 === PlatformEditorTypes.dxTagBox ? (
                  <SimpleItemDx
                    key={'formItem-' + i}
                    {...formItem}
                    render={() => (
                      <TagBoxEditorComponent
                        value={formData[formItem.dataField!] || []}
                        setDefaultValue={false}
                        values={formData}
                        options={formItem.tagBoxOptions}
                        col={formItem.colData}
                        onValueChanged={(e: any) => {
                          setFormData({ ...formData, [formItem.dataField!]: e })
                        }}
                        editorOptions={{
                          ...formItem.editorOptions,
                          ...(mode === 'view' ? { readOnly: true } : {}),
                        }}
                      ></TagBoxEditorComponent>
                    )}
                  >
                    <LabelDx text={formItem.name} />
                  </SimpleItemDx>
                ) : formItem.editorType2 === PlatformEditorTypes.dxGridBox ? (
                  <SimpleItemDx
                    key={'formItem-' + i}
                    {...formItem}
                    render={() => (
                      <GridBoxEditorComponent
                        value={formData[formItem.dataField!] || []}
                        values={formData}
                        options={formItem.gridBoxOptions}
                        col={formItem.colData}
                        onValueChanged={(e: any) => {
                          setFormData({ ...formData, [formItem.dataField!]: e })
                        }}
                        editorOptions={{
                          ...formItem.editorOptions,
                          ...(mode === 'view' ? { readOnly: true } : {}),
                        }}
                      ></GridBoxEditorComponent>
                    )}
                  >
                    <LabelDx text={formItem.name} />
                  </SimpleItemDx>
                ) : (
                  <SimpleItemDx
                    cssClass="font-semibold"
                    key={'formItem-' + i}
                    {...formItem}
                    editorOptions={{
                      ...formItem.editorOptions,
                      ...(mode === 'view' ? { readOnly: true } : { autoFocus: i === 1 }),
                      buttons: (formItem.editorOptions?.buttons || []).map((btn: any) => {
                        if (btn?.options?.onClick && typeof btn.options.onClick === 'string') {
                          const origClick = eval(`(${btn.options.onClick})`)
                          btn.options.onClick = (e: any) => {
                            origClick({
                              ...e,
                              formData: formDataRef.current,
                              fieldName: formItem.dataField,
                              mode,
                            })
                          }
                        }
                        return btn
                      }),
                    }}
                  />
                )
              })}
            </GroupItemDx>
          )
        })}
      </FormDx>
    </form>
  )
}

export default FormDevExpress
