import React, { useEffect, useState } from 'react'
import { isEmpty } from 'lodash'
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout'
import FormInput from '@/Components/FormInput'
import Button from '@/Components/Button'
import { Head, useForm } from '@inertiajs/react'
import FormInputWith from '@/Components/FormInputWith'
import LocationSelectionInput from '../Location/SelectionInput'
import Checkbox from '@/Components/Checkbox'
export default function Form(props) {
const { voucher, levels } = props
const [use_level, setUseLevel] = useState(false)
const { data, setData, post, processing, errors } = useForm({
username: '',
password: '',
discount: 0,
display_price: 0,
price_poin: 0,
quota: '',
profile: '',
comment: '',
expired: '',
expired_unit: 'Hari',
location_id: null,
prices: null,
})
const handleOnChange = (event) => {
setData(
event.target.name,
event.target.type === 'checkbox'
? event.target.checked
? 1
: 0
: event.target.value
)
}
const handleUseLevel = () => {
setUseLevel(!use_level)
if (!use_level === true) {
const prices = levels.map((level) => {
return {
name: level.name,
customer_level_id: level.id,
display_price: '0',
}
})
setData('prices', prices)
return
}
setData('prices', null)
}
const handleSetLevelPrice = (id, value) => {
setData(
'prices',
data.prices.map((price) => {
if (price.customer_level_id === id) {
return {
...price,
display_price: value,
}
}
return price
})
)
}
const handleSubmit = () => {
if (isEmpty(voucher) === false) {
post(route('voucher.update', voucher))
return
}
post(route('voucher.store'))
}
useEffect(() => {
if (isEmpty(voucher) === false) {
let prices = null
if (voucher.prices.length > 0) {
setUseLevel(true)
prices = voucher.prices.map((price) => {
return {
...price,
name: price.level.name,
}
})
}
setData({
username: voucher.username,
password: voucher.password,
discount: voucher.discount,
display_price: voucher.display_price,
price_poin: voucher.price_poin,
quota: voucher.quota,
profile: voucher.profile,
comment: voucher.comment,
expired: voucher.expired,
expired_unit: voucher.expired_unit,
location_id: voucher.location_id,
prices: prices,
})
}
}, [voucher])
return (
{errors.prices}
)}