import { useEffect } from "react"
import { usePage } from "@inertiajs/react"
import useFormBuilder from "@/utils/useFormBuilder"
import FormBuilder from "@/Components/FormBuilder"
import { slugify, useSearchParams } from "@/utils/format"
import { handleSelectReload } from "@/utils/useFormChange"

function MainForm({ isEdit = false, formOptions = {}, BackButton = null }) {
  const formConfig = { isEdit, getProperties, formOptions }
  const builderProps = useFormBuilder(formConfig)
  const { data, setData } = builderProps.form

  return <FormBuilder {...builderProps} BackButton={BackButton} />
}

const getProperties = (state) => {
  const { props, data, setData } = state
  const { params } = useSearchParams(props.location)

  const properties = [
    [
      {
        form: "input",
        props: {
          name: "name",
          label: "Nama",
          type: "text",
        },
      },
      {
        form: "select",
        props: {
          name: "period_type",
          label: "Tipe Periode",
          options: props.period_types,
          prefix: "category.period_type",
        },
      },
      {
        form: "select",
        props: {
          name: "status",
          label: "Status",
          options: props.status,
          prefix: "category.status",
        },
      },
    ],
    [
      {
        form: "select",
        props: {
          isReactSelect: true,
          isVirtualized: true,
          name: "parent_id",
          label: "Master Kategori",
          value: data.parent_id,
          options: props.parent_categories,
          handleChange: (e) => handleSelectReload({ e, name: "parent_id", ...state }),
          bottomLabel: "Jika dikosongkan akan menjadi kategori level 1",
        },
      }
    ]
  ]

  return properties
}

const PropertiesProvider = ({ children }) => {
  return children(getProperties)
}

MainForm.PropertiesProvider = PropertiesProvider

const CategoryMainForm = MainForm
export default CategoryMainForm
