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"

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: "select",
        props: {
          name: "type",
          label: "Tipe",
          options: props.types,
          prefix: "user_bank.type",
          handleChange: (e) => {
            setData({
              ...data,
              type: e?.target?.value,
              user_id: null,
              company_id: null
            })
          }
        },
      },
    ],
    [
      {
        form: "select",
        isHidden: data.type != 'personal',
        props: {
          name: "user_id",
          label: "Pengguna",
          options: props.users,
          isReactSelect: true,
          isVirtualized: true,
          handleChange: (e) => setData("user_id", e?.value),
        },
      },
      {
        form: "select",
        isHidden: data.type != 'company',
        props: {
          name: "company_id",
          label: "Perusahaan",
          options: props.companies,
          isReactSelect: true,
          isVirtualized: true,
          handleChange: (e) => setData("company_id", e?.value),
        },
      },
      {
        form: "select",
        props: {
          name: "bank_id",
          label: "Bank",
          options: props.banks,
          isReactSelect: true,
          isVirtualized: true,
          handleChange: (e) => setData("bank_id", e?.value),
        },
      },
      {
        form: "input",
        props: {
          name: "branch",
          label: "Cabang",
          type: "text",
        },
      },
    ],
    [
      {
        form: "input",
        props: {
          name: "account_number",
          label: "No. Rekening",
          type: "number",
        },
      },
      {
        form: "input",
        props: {
          name: "account_name",
          label: "Nama Rekening",
          type: "text",
        },
      },
    ],
    [
      {
        form: "select",
        props: {
          name: "status",
          label: "Status",
          options: props.status,
          prefix: "user_bank.status",
        },
      },
    ],
  ]

  return properties
}

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

MainForm.PropertiesProvider = PropertiesProvider

const UserBankMainForm = MainForm
export default UserBankMainForm
