import { JenisBelanjaList } from '@/services/referensi/jenisBelanja-service'
import { JenisKegiatanList } from '@/services/referensi/jenisKegiatan-service'
import { JenisTagihanList } from '@/services/referensi/jenisTagihan-service'
import { PersyaratanCreate, PersyaratanUpdate } from '@/services/referensi/persyaratan-service'
import { FieldArray, Formik } from 'formik'
import { Button } from 'primereact/button'
import { Dialog } from 'primereact/dialog'
import { Dropdown } from 'primereact/dropdown'
import { InputText } from 'primereact/inputtext'
import { InputTextarea } from 'primereact/inputtextarea'
import { useEffect, useState } from 'react'

export default function FormPersyaratan({ dialogForm, setDialogForm, dataEdit, setDataEdit, refresh, toast }) {
	const [optionJenisTagihan, setOptionJenisTagihan] = useState([])
	const [optionJenisBelanja, setOptionJenisBelanja] = useState([])
	const [optionJenisKegiatan, setOptionJenisKegiatan] = useState([])

	useEffect(() => {
		JenisTagihanList({ draw: 0 }).then((res) => setOptionJenisTagihan(res.data))
		JenisBelanjaList({ draw: 0 }).then((res) => setOptionJenisBelanja(res.data))
		JenisKegiatanList({ draw: 0 }).then((res) => setOptionJenisKegiatan(res.data))
	}, [])

	return (
		<>
			<Formik
				initialValues={{
					syarat_id: dataEdit.syarat_id || '',
					jenis_tagihan: dataEdit.jenis_tagihan_id || '',
					jenis_belanja: dataEdit.jenis_belanja_id || '',
					jenis_kegiatan: dataEdit.jenis_kegiatan_id || '',
					syarat: [{}],
				}}
				validate={(data) => {
					let errors = {}
					if (!data.jenis_tagihan) errors.jenis_tagihan = 'Jenis Tagihan is required.'
					if (!data.jenis_belanja) errors.jenis_belanja = 'Jenis Belanja is required.'
					if (!data.jenis_kegiatan) errors.jenis_kegiatan = 'Jenis Kegiatan is required.'
					// if (!data.syarat) errors.syarat = 'Syarat Dokumen is required.'
					// if (!data.keterangan) errors.keterangan = 'Keterangan is required.'
					return errors
				}}
				onSubmit={(data) => {
					if (data.syarat_id) {
						PersyaratanUpdate(data).then((res) => {
							if (res.status === 'success') {
								refresh(Math.random)
								setDataEdit([])
								setDialogForm(false)
								toast.current.show({
									severity: 'success',
									detail: res.message,
									closable: false,
								})
							} else {
								setDialogForm(false)
								toast.current.show({
									severity: 'error',
									detail: res.message,
									closable: false,
								})
							}
						})
					} else {
						PersyaratanCreate(data).then((res) => {
							if (res.status === 'success') {
								refresh(Math.random)
								setDataEdit([])
								setDialogForm(false)
								toast.current.show({
									severity: 'success',
									detail: res.message,
									closable: false,
								})
							} else {
								setDialogForm(false)
								toast.current.show({
									severity: 'error',
									detail: res.message,
									closable: false,
								})
							}
						})
					}
				}}
				validateOnChange={false}
			>
				{({ values, errors, handleChange, handleSubmit, isSubmitting, resetForm }) => {
					const dialogFooter = (
						<div className='flex justify-end'>
							<Button
								type='submit'
								label='Cancel'
								className='p-button-sm p-button-secondary'
								onClick={() => {
									resetForm()
									setDialogForm(false)
								}}
							/>
							<Button
								type='submit'
								label='Save'
								className='p-button-sm p-button-primary'
								onClick={handleSubmit}
								loading={isSubmitting}
							/>
						</div>
					)

					return (
						<Dialog
							header={values.syarat_id ? 'Update Persyaratan' : 'Add Persyaratan'}
							className='p-dialog-form'
							visible={dialogForm}
							draggable={false}
							resizable={false}
							position={'center'}
							closable={false}
							style={{ width: '45vw' }}
							footer={dialogFooter}
						>
							<form onSubmit={handleSubmit}>
								<div className='p-fluid grid gap-y-2'>
									<div className='field col-12 md:col-4'>
										<label className='block'>Jenis Tagihan</label>
										<Dropdown
											panelClassName='p-dropdown-form'
											name='jenis_tagihan'
											options={optionJenisTagihan}
											optionLabel='nama'
											optionValue='jenis_id'
											value={values.jenis_tagihan}
											onChange={handleChange}
											showClear={values.jenis_tagihan ? true : false}
											scrollHeight='200px'
											placeholder='Select Jenis Tagihan'
										/>
										{errors.jenis_tagihan && <div className='text-red-500 text-xs'>{errors.jenis_tagihan}</div>}
									</div>
									<div className='field col-12 md:col-4'>
										<label className='block'>Jenis Belanja</label>
										<Dropdown
											panelClassName='p-dropdown-form'
											name='jenis_belanja'
											options={optionJenisBelanja}
											optionLabel='nama'
											optionValue='jenis_id'
											value={values.jenis_belanja}
											onChange={handleChange}
											showClear={values.jenis_belanja ? true : false}
											scrollHeight='200px'
											placeholder='Select Jenis Belanja'
										/>
										{errors.jenis_belanja && <div className='text-red-500 text-xs'>{errors.jenis_belanja}</div>}
									</div>
									<div className='field col-12 md:col-4'>
										<label className='block'>Jenis Kegiatan</label>
										<Dropdown
											panelClassName='p-dropdown-form'
											name='jenis_kegiatan'
											options={optionJenisKegiatan}
											optionLabel='nama'
											optionValue='jenis_id'
											value={values.jenis_kegiatan}
											onChange={handleChange}
											showClear={values.jenis_kegiatan ? true : false}
											scrollHeight='200px'
											placeholder='Select Jenis Kegiatan'
										/>
										{errors.jenis_kegiatan && <div className='text-red-500 text-xs'>{errors.jenis_kegiatan}</div>}
									</div>
									<FieldArray
										name='syarat'
										render={(arrayHelpers) => (
											<div className=''>
												<label className='block'>Syarat</label>
												<div className='flex flex-col gap-1'>
													{values.syarat.map((syarat, index) => (
														<div key={index} className='field col-12 flex gap-2 items-center'>
															<div className='border p-3 rounded shadow my-2 w-full flex flex-col gap-2'>
																<div className='flex flex-col gap-1'>
																	<label className='block'>Nama Syarat {index + 1}</label>
																	<InputText
																		className='p-inputtext-sm'
																		name={`syarat.${index}.syarat`}
																		value={values.syarat[index].syarat}
																		onChange={handleChange}
																		placeholder='Masukkan Syarat Dokumen'
																	/>
																	{errors.syarat && errors.syarat[index] && (
																		<div className='text-red-500 text-xs'>{errors.syarat[index].syarat}</div>
																	)}
																</div>
																<div className='flex flex-col gap-1'>
																	<label className='block'>Keterangan Syarat {index + 1}</label>
																	<InputTextarea
																		name={`syarat.${index}.keterangan`}
																		rows={3}
																		cols={30}
																		value={values.syarat[index].keterangan}
																		onChange={handleChange}
																		placeholder='Masukkan Keterangan'
																	/>
																</div>
															</div>
															{index > 0 && (
																<Button
																	icon='pi pi-times'
																	className='p-button-danger p-button-sm'
																	onClick={() => arrayHelpers.remove(index)}
																/>
															)}
														</div>
													))}
													<div className='w-fit relative left-1/2 -translate-x-1/2'>
														<Button
															type='button'
															icon='pi pi-plus'
															className='p-button-sm'
															label='Tambah Syarat'
															onClick={() => arrayHelpers.push({ syarat: '', keterangan: '' })}
														/>
													</div>
												</div>
											</div>
										)}
									/>
								</div>
							</form>
						</Dialog>
					)
				}}
			</Formik>
		</>
	)
}
