import { useForm, usePage } from "@inertiajs/react"
import WithModal from "@/Components/WithModal"
import { FormProperty } from "@/Components/FormBuilder"
import useFormChange from "@/utils/useFormChange"
import { useRef } from "react"

export default function FormModal({ onClose, onSuccess, id = 'create_vendor_modal' }) {
  const { props } = usePage()

  const form = useForm({
    ref_url: `${props.location}?ref=${props.location}`,
    name: '',
    company_name: '',
    phone: '',
    city: '',
    status: 'active',
    address: '',
  })

  const { data, setData, post, processing, errors, reset } = form

  const handleChange = (e) => {
    const { name, value } = useFormChange(e, data)
    setData((state) => ({
      ...state,
      [name]: value,
    }))
  }

  const handleSubmit = (closeModal) => {
    post("/admin/vendors", {
      onSuccess: () => {
        reset()
        closeModal()
        onSuccess && onSuccess()
      },
      onError: (err) => {
        console.error(err)
      }
    })
  }

  const inputProps = { data, setData, handleChange, errors }
  const properties = getProperties({ props, data, setData, inputProps })

  const backButtonRef = useRef()

  return (
    <WithModal
      type={id}
      backdrop
    >
      <h3 className="font-bold text-lg mb-4">Tambah Vendor</h3>

      <FormProperty
        properties={properties}
        inputProps={inputProps}
      />

      <div className="modal-action">
        <button
          ref={backButtonRef}
          type="button"
          className="btn btn-sm btn-ghost"
          onClick={onClose}
        >
          Batal
        </button>
        <button
          onClick={() => handleSubmit(() => onClose())}
          className="btn btn-sm btn-primary"
          disabled={processing}
        >
          {processing && <span className="loading loading-spinner loading-xs"></span>}
          Simpan
        </button>
      </div>
    </WithModal>
  )
}

const getProperties = (state) => {
  const { props } = state

  const properties = [
    [
      {
        form: "input",
        props: {
          name: "name",
          label: "Nama PIC",
          type: "text",
          required: true,
        },
      },
      {
        form: "input",
        props: {
          name: "company_name",
          label: "Nama Perusahaan",
          type: "text",
          required: true,
        },
      },
    ],
    [
      {
        form: "input",
        props: {
          name: "phone",
          label: "No. HP PIC",
          type: "text",
        },
      },
      {
        form: "input",
        props: {
          name: "city",
          label: "Kota",
          type: "text",
        },
      },
    ],
    [
      {
        form: "textarea",
        props: {
          name: "address",
          label: "Alamat",
        },
      },
    ],
  ]

  return properties
}
