import { Belakang } from '@/components/Layouts'
import { Judul, LabelInput } from '@/components/TextCustom'
import { DetailSPPGet, NoSPPListGet } from '@/services/pengajuan-tagihan/integrasi-service'
import { TagihanAddDetail, TagihanCreate, TagihanSubmit } from '@/services/pengajuan-tagihan/tagihan-service'
import { AkunList } from '@/services/referensi/akun-service'
import { JenisKegiatanList } from '@/services/referensi/jenisKegiatan-service'
import { PersyaratanSearch } from '@/services/referensi/persyaratan-service'
import { useFormik } from 'formik'
import { fetchAPI } from 'lib/fetch'
import 'moment/locale/id'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { Accordion, AccordionTab } from 'primereact/accordion'
import { BlockUI } from 'primereact/blockui'
import { BreadCrumb } from 'primereact/breadcrumb'
import { Button } from 'primereact/button'
import { Calendar } from 'primereact/calendar'
import { Card } from 'primereact/card'
import { Checkbox } from 'primereact/checkbox'
import { Chips } from 'primereact/chips'
import { Dropdown } from 'primereact/dropdown'
import { FileUpload } from 'primereact/fileupload'
import { InputText } from 'primereact/inputtext'
import { InputTextarea } from 'primereact/inputtextarea'
import { Toast } from 'primereact/toast'
import { useEffect, useRef, useState } from 'react'
import Swal from 'sweetalert2'

export default function FormPengajuanTagihan({ optionJenisTagihan = null, optionJenisBelanja = null }) {
	const toast = useRef(null)
	const router = useRouter()
	const [countJenisTagihan, setCountJenisTagihan] = useState(0)
	const [optionAkun, setOptionAkun] = useState([])
	const [tagihanID, setTagihanID] = useState('')
	const [kirimLoading, setKirimLoading] = useState(false)
	const [optionJenisKegiatan, setOptionJenisKegiatan] = useState([])
	const [statusDraft, setStatusDraft] = useState(false)
	const [optionNoSpp, setOptionNoSpp] = useState([])
	const [jenisSPP, setJenisSPP] = useState('')
	const [uraianSPP, setUraianSPP] = useState('')
	const [itsGU, setItsGU] = useState(false)
	const [checkedGUGabungan, setCheckedGUGabungan] = useState(false)

	const formik = useFormik({
		initialValues: {
			no_spp: '',
			tgl_spp: '',
			jenis_tagihan: '',
			kode_jenis_spp: '',
			spp_gabungan: [],
		},
		validate: (data) => {
			let errors = {}
			if (!data.no_spp) errors.no_spp = 'Nomor SPP is required.'
			if (!data.tgl_spp) errors.tgl_spp = 'Tanggal SPP is required.'
			if (!data.jenis_tagihan) errors.jenis_tagihan = 'Jenis Tagihan is required.'
			return errors
		},
		onSubmit: (data) => {
			const tanggalAsli = data.tgl_spp

			/**
			 * Check tagihan if > 0 just add tagihan
			 * else request tagihan id
			 */
			if (countJenisTagihan > 0) {
				setCountJenisTagihan(countJenisTagihan + 1)
			} else {
				TagihanCreate(data)
					.then((res) => {
						if (res.status === 'success') {
							Object.assign(data, { tgl_spp: tanggalAsli })
							setCountJenisTagihan(countJenisTagihan + 1)
							formikDetailTagihan.setFieldValue('tagihan_id', res.data.tagihan_id)
							setTagihanID(res.data.tagihan_id)
						} else {
							Object.assign(data, { tgl_spp: tanggalAsli })
							toast.current.show({
								severity: 'error',
								detail: res.message,
								closable: false,
							})
						}
					})
					.catch((err) => {
						console.log(err)
						toast.current.show({
							severity: 'error',
							detail: 'Error while creating data',
							closable: false,
						})
					})
			}
		},
	})

	// NOMER SPP
	useEffect(() => {
		NoSPPListGet()
			.then((res) => setOptionNoSpp(res.data))
			.catch((err) => console.log(err))
	}, [])

	useEffect(() => {
		DetailSPPGet({ no_spp: formik.values.no_spp }).then((res) => {
			if (res.data.akun.length > 0) {
				setJenisSPP(res.data.jenis_spp)
				setUraianSPP(res.data.uraian)
				formik.setFieldValue('tgl_spp', new Date(res.data.tanggal_spp))
				setOptionAkun(res.data.akun)
			} else {
				let params = {}
				params.draw = 0
				setJenisSPP('')
				setUraianSPP('')
				formik.setFieldValue('tgl_spp', new Date())
				AkunList(params).then((res) => {
					setOptionAkun(res.data)
				})
			}
		})
	}, [])

	const formikDetailTagihan = useFormik({
		initialValues: {
			tagihan_id: '',
			detail_tagihan: [],
			dataIndex: 0, //* For select data index
		},
		validate: (data) => {
			let errorsArray = []
			let errors = {}

			if (!data.detail_tagihan[data.dataIndex]) {
				errors.jenis_belanja = 'Jenis Belanja is required.'
				errors.jenis_kegiatan = 'Jenis Kegiatan is required.'
				errors.akun = 'Akun is required.'
			}
			if (data.detail_tagihan[data.dataIndex] && data.detail_tagihan[data.dataIndex].jenis_belanja === '') {
				errors.jenis_belanja = 'Jenis Belanja is required dong.'
			}
			if (data.detail_tagihan[data.dataIndex] && !data.detail_tagihan[data.dataIndex].jenis_kegiatan) {
				errors.jenis_kegiatan = 'Jenis Kegiatan is required.'
			}
			if (data.detail_tagihan[data.dataIndex] && !data.detail_tagihan[data.dataIndex].akun_id) {
				errors.akun = 'Akun is required.'
			}

			if (Object.keys(errors).length > 0) {
				errorsArray.push({ dataIndex: countJenisTagihan - 1, errors })
			}

			return errorsArray
		},
		onSubmit: (data) => {
			formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].loading', true)

			/**
			 * *Filter data detail tagihan follow the button kirim
			 */
			const filterData = data.detail_tagihan.find((item, i) => i === data.dataIndex)

			/**
			 * *Create new format data detail tagihan reference to API
			 */
			const dataKirim = {
				tagihan_id: data.tagihan_id,
				detail_tagihan: [filterData],
			}

			TagihanAddDetail(dataKirim)
				.then((res) => {
					if (res.status === 'ok') {
						toast.current.show({
							severity: 'success',
							detail: res.message,
							closable: false,
						})
						if (statusDraft) {
							router.push('/pengajuan-tagihan')
						}
						/**
						 * *Add status to detail tagihan object for check if it is sended or not
						 */
						formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].status', true)
						formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].loading', false)
					} else {
						toast.current.show({
							severity: 'error',
							detail: res.message,
							closable: false,
						})
						/**
						 * *Add status to detail tagihan object for check if it is sended or not
						 */
						formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].status', false)
						formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].loading', false)
					}
				})
				.catch((err) => {
					console.log(err)
					toast.current.show({
						severity: 'error',
						detail: 'Error saat pembuatan data/file belum diupload',
						closable: false,
					})
					/**
					 * *Add status to detail tagihan object for check if it is sended or not
					 */
					formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].status', false)
					formikDetailTagihan.setFieldValue('detail_tagihan[' + data.dataIndex + '].loading', false)
				})
		},
		validateOnChange: false,
	})

	/**
	 * *Message error for formik
	 */
	const isFieldValid = (field) => !!(formik.touched[field] && formik.errors[field])
	const errorFieldMessage = (field) => {
		return (
			isFieldValid(field) && (
				<small className='p-error' style={{ fontSize: '11px' }}>
					{formik.errors[field]}
				</small>
			)
		)
	}

	/**
	 * *Message error for formik detail tagihan
	 */
	const isFieldValidDetail = (index, field) =>
		formikDetailTagihan.errors[0] &&
		formikDetailTagihan.errors[0].dataIndex === index &&
		formikDetailTagihan.errors[0].errors[field]
	const errorFieldMessageDetail = (index, field) => {
		return (
			isFieldValidDetail(index, field) && (
				<small className='p-error' style={{ fontSize: '11px' }}>
					{formikDetailTagihan.errors[0].errors[field]}
				</small>
			)
		)
	}

	/**
	 * *Card Detail Tagihan
	 */
	const headerTemplate = (index) => {
		const handleDelete = (index) => {
			formikDetailTagihan.setValues({
				...formikDetailTagihan.values,
				detail_tagihan: formikDetailTagihan.values.detail_tagihan.filter((item, i) => i !== index),
			})
			setCountJenisTagihan(countJenisTagihan - 1)
		}

		return (
			<div className='flex justify-between items-center w-full'>
				<p>Tagihan {index + 1}</p>
				<Button
					type='button'
					icon='pi pi-times'
					className='p-button-rounded p-button-danger p-button-text button-close-tagihan'
					aria-label='Cancel'
					onClick={() => handleDelete(index)}
					title='Delete tagihan'
				/>
			</div>
		)
	}

	/**
	 * *Dropdown list jenis kegiatan
	 * *When jenis kegiatan change hit API to get list syarat
	 */
	const changeJenisKegiatan = (event, index) => {
		formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].syarat`, [])
		formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].jenis_kegiatan`, event.value)
		PersyaratanSearch({
			jenis_tagihan_id: formik.values.jenis_tagihan,
			jenis_belanja_id: formikDetailTagihan.values.detail_tagihan[index].jenis_belanja,
			jenis_kegiatan_id: event.value,
		})
			.then((res) => {
				if (res.data) {
					res.data.map((item, index2) => {
						formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].syarat[${index2}].syarat_id`, item.syarat_id)
						formikDetailTagihan.setFieldValue(
							`detail_tagihan[${index}].syarat[${index2}].syarat_dokumen`,
							item.syarat_dokumen
						)
						formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].syarat[${index2}].keterangan`, item.keterangan)
					})
				} else {
					formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].syarat`, [])
					toast.current.show({
						severity: 'info',
						detail: 'Data syarat kosong',
						closable: false,
					})
				}
			})
			.catch(() => {
				toast.current.show({
					severity: 'error',
					detail: 'Error while get data',
					closable: false,
				})
			})
	}

	/**
	 * *Change Jenis Belanja
	 * *Reset form detail tagihan
	 */
	const changeJenisBelanja = (event, index) => {
		formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].syarat`, [])
		formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].jenis_belanja`, event.value)

		/**
		 * SHOW LIST JENIS KEGIATAN WHERE JENIS_BELANJA_ID
		 */
		JenisKegiatanList({ jenis_belanja_id: event.value, draw: 0 })
			.then((res) => setOptionJenisKegiatan(res.data))
			.catch((err) => console.log(err))
	}

	/**
	 * *End of Dropdown list jenis kegiatan
	 */

	/**
	 * *Form Detail Tagihan
	 * *Button Submit and draft
	 */
	const handleSubmitDetailTagihan = (e, { draft, index }) => {
		e.preventDefault()
		setStatusDraft(draft)
		formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].draft`, draft)
		formikDetailTagihan.handleSubmit()
	}

	const tagihanList = []
	const tagihan = (index) => {
		const customBase64Uploader = async (event) => {
			// convert file to base64 encoded
			const file = event.files[0]
			if (file) {
				if (file.type === 'application/pdf') {
					const reader = new FileReader()
					reader.readAsDataURL(file)

					reader.onloadend = function () {
						const base64data = reader.result
						formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file`, base64data)
						formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file_name`, file.name)
					}
					toast.current.show({
						severity: 'success',
						detail: 'File berhasil diupload',
						closable: false,
					})
				} else {
					event.options.clear()
					toast.current.show({
						severity: 'error',
						detail: 'Invalid format file',
						closable: false,
					})
					formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file`, null)
					formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file_name`, null)
				}
			}
		}

		return (
			<AccordionTab key={index} headerTemplate={headerTemplate(index)} className={`accordion-tab-${index}`}>
				<BlockUI
					blocked={
						formikDetailTagihan.values.detail_tagihan[index] !== undefined &&
						formikDetailTagihan.values.detail_tagihan[index].status
							? true
							: false
					}
					className='block-ui-custom cursor-not-allowed'
				>
					<div className='p-fluid grid grid-cols-2 gap-3'>
						{/* JENIS BELANJA */}
						<div className='field col-12 md:col-4'>
							<LabelInput>Jenis Belanja</LabelInput>
							<Dropdown
								panelClassName='p-dropdown-form'
								name={`detail_tagihan[${index}].jenis_belanja`}
								options={optionJenisBelanja}
								optionLabel='nama'
								optionValue='jenis_id'
								value={
									formikDetailTagihan.values.detail_tagihan[index] !== undefined
										? formikDetailTagihan.values.detail_tagihan[index].jenis_belanja
										: formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].jenis_belanja`, '')
								}
								onChange={(e) => changeJenisBelanja(e, index)}
								showClear={formikDetailTagihan.values.detail_tagihan[index] !== undefined ? true : false}
								scrollHeight='200px'
								placeholder='Select Jenis Belanja'
							/>
							{errorFieldMessageDetail(index, 'jenis_belanja')}
						</div>
						{/* JENIS KEGIATAN */}
						<div className='field col-12 md:col-4'>
							<LabelInput>Jenis Kegiatan</LabelInput>
							<Dropdown
								panelClassName='p-dropdown-form'
								name={`detail_tagihan[${index}].jenis_kegiatan`}
								options={optionJenisKegiatan}
								optionLabel='nama'
								optionValue='jenis_id'
								value={
									formikDetailTagihan.values.detail_tagihan[index] !== undefined
										? formikDetailTagihan.values.detail_tagihan[index].jenis_kegiatan
										: formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].jenis_kegiatan`, '')
								}
								onChange={(e) => changeJenisKegiatan(e, index)}
								showClear={formikDetailTagihan.values.detail_tagihan[index] !== undefined ? true : false}
								scrollHeight='200px'
								placeholder='Select Jenis Kegiatan'
								filter
							/>
							{errorFieldMessageDetail(index, 'jenis_kegiatan')}
						</div>
					</div>
					{/* SYARAT */}
					<div className='p-fluid grid grid-cols-2 gap-3'>
						<div className='md:col-4 my-3'>
							<LabelInput>Syarat</LabelInput>
							<div className='relative mt-2 flex overflow-auto h-96'>
								<table className='w-full text-sm text-left  '>
									<thead className='text-xs uppercase bg-gray-100 sticky top-0'>
										<tr>
											<th scope='col' className='py-3 px-6'>
												Persyaratan
											</th>
											<th scope='col' className='py-3 px-6'>
												Keterangan
											</th>
										</tr>
									</thead>
									<tbody>
										{formikDetailTagihan.values.detail_tagihan[index] &&
											formikDetailTagihan.values.detail_tagihan[index].syarat &&
											formikDetailTagihan.values.detail_tagihan[index].syarat.map((item, index2) => (
												<tr className='bg-white border-b' key={index2}>
													<td scope='row' className='py-4 px-6'>
														{item.syarat_dokumen}
													</td>
													<td scope='row' className='py-4 px-6'>
														{item.keterangan}
													</td>
												</tr>
											))}
									</tbody>
								</table>
							</div>
						</div>
						<div className='upload-all my-3'>
							<LabelInput>Upload Syarat</LabelInput>
							<div className='py-4 px-6'>
								<FileUpload
									name='upload-syarat'
									url={'#'}
									accept='.pdf'
									// maxFileSize={1000000}
									emptyTemplate={<p className='m-0'>Drag and drop files to here to upload.</p>}
									customUpload
									uploadHandler={(e) => customBase64Uploader(e)}
									onClear={() => formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file`, false)}
									onRemove={() => formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].file`, false)}
									uploadOptions={{
										className:
											formikDetailTagihan.values.detail_tagihan[index] !== undefined &&
											'file' in formikDetailTagihan.values.detail_tagihan[index]
												? 'p-disabled'
												: '',
									}}
									cancelOptions={{
										className:
											formikDetailTagihan.values.detail_tagihan[index] !== undefined &&
											'file' in formikDetailTagihan.values.detail_tagihan[index]
												? 'p-disabled'
												: '',
									}}
								/>
							</div>
						</div>
					</div>
					{/* AKUN */}
					<div className='p-fluid'>
						{optionNoSpp.length > 0 ? (
							<div className='field col-6 md:col-4 my-3 w-1/2'>
								<LabelInput>Akun</LabelInput>
								<Dropdown
									panelClassName='p-dropdown-form dd-panel-custom'
									name={`detail_tagihan[${index}].akun_id`}
									options={optionAkun}
									// optionLabel={(item) => `${item.KODE_AKUN} - ${item.URAIAN}`}
									// optionValue='KODE_AKUN'
									value={
										formikDetailTagihan.values.detail_tagihan[index] !== undefined
											? formikDetailTagihan.values.detail_tagihan[index].akun_id
											: formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].akun_id`, '')
									}
									onChange={formikDetailTagihan.handleChange}
									showClear={formikDetailTagihan.values.detail_tagihan[index] !== undefined ? true : false}
									scrollHeight='300px'
									placeholder='Select Akun'
									filter
									maxLength={100}
								/>
								{errorFieldMessageDetail(index, 'akun')}
							</div>
						) : (
							<div className='field col-6 md:col-4 my-3 w-1/2'>
								<LabelInput>Akun</LabelInput>
								<Dropdown
									panelClassName='p-dropdown-form dd-panel-custom'
									name={`detail_tagihan[${index}].akun_id`}
									options={optionAkun}
									optionLabel={(item) => `${item.akun_id} - ${item.nama}`}
									optionValue='akun_id'
									value={
										formikDetailTagihan.values.detail_tagihan[index] !== undefined
											? formikDetailTagihan.values.detail_tagihan[index].akun_id
											: formikDetailTagihan.setFieldValue(`detail_tagihan[${index}].akun_id`, '')
									}
									onChange={formikDetailTagihan.handleChange}
									showClear={formikDetailTagihan.values.detail_tagihan[index] !== undefined ? true : false}
									scrollHeight='300px'
									placeholder='Select Akun'
									filter
									maxLength={100}
								/>
								{errorFieldMessageDetail(index, 'akun')}
							</div>
						)}

						<div className='field col-12 md:col-4 my-3'>
							<LabelInput>Keperluan</LabelInput>
							<InputTextarea
								name={`detail_tagihan[${index}].keperluan`}
								rows={5}
								cols={30}
								value={
									formikDetailTagihan.values.detail_tagihan[index] !== undefined
										? formikDetailTagihan.values.detail_tagihan[index].keperluan
										: ''
								}
								onChange={formikDetailTagihan.handleChange}
								placeholder='Masukkan detail keperluan'
							/>
						</div>
					</div>
				</BlockUI>

				{/* BUTTON DRAFT, SIMPAN AND MESSAGE */}
				<div className='flex justify-center gap-2 mt-3'>
					{formikDetailTagihan.values.detail_tagihan[index] !== undefined &&
					formikDetailTagihan.values.detail_tagihan[index].status === true ? (
						<div className='flex flex-col'>
							<label className='p-2 bg-green-300 rounded shadow text-center'>
								<i className='pi pi-check'></i> Tagihan Berhasil dikirim/draft
							</label>
							<small className='text-red-400'>Tagihan ini hanya bisa didelete, tidak bisa diubah kembali!</small>
						</div>
					) : (
						<>
							<Button
								type='submit'
								label='Draft'
								icon='pi pi-save'
								className='p-button-sm p-button-info'
								onClick={(e) => handleSubmitDetailTagihan(e, { draft: true, index })}
								loading={
									formikDetailTagihan.values.detail_tagihan[index] &&
									formikDetailTagihan.values.detail_tagihan[index].loading
										? formikDetailTagihan.values.detail_tagihan[index].loading
										: false
								}
							/>
							<Button
								type='submit'
								label='Simpan'
								icon='pi pi-send'
								className='p-button-sm p-button-success'
								onClick={(e) => handleSubmitDetailTagihan(e, { draft: false, index })}
								loading={
									formikDetailTagihan.values.detail_tagihan[index] &&
									formikDetailTagihan.values.detail_tagihan[index].loading
										? formikDetailTagihan.values.detail_tagihan[index].loading
										: false
								}
							/>
						</>
					)}
				</div>
			</AccordionTab>
		)
	}
	for (let index = 0; index < countJenisTagihan; index++) {
		tagihanList.push(tagihan(index))
	}
	/**
	 * *End Detail Tagihan
	 * *End Card Detail Tagihan
	 */

	/**
	 * *Breadcrumb
	 */
	const items = [{ label: 'Pengajuan Tagihan', url: '/pengajuan-tagihan' }, { label: 'Form' }]
	const home = { icon: 'pi pi-home', url: '/dashboard' }

	const handleTambahTagihan = (e) => {
		e.preventDefault()

		Swal.fire({
			title: 'Apakah data yang diinputkan sudah benar benar?',
			// text: "Kamu tidak bisa pakai !",
			icon: 'question',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: 'Ya, benar!',
			cancelButtonText: 'Tidak',
		}).then((result) => {
			if (result.isConfirmed) {
				Swal.fire({
					title: 'Pastikan kembali!',
					text: 'Kamu tidak bisa pakai data ini kembali!',
					icon: 'question',
					showCancelButton: true,
					confirmButtonColor: '#3085d6',
					cancelButtonColor: '#d33',
					confirmButtonText: 'Ya, benar!',
					cancelButtonText: 'Tidak',
				}).then((result) => {
					if (result.isConfirmed) {
						formikDetailTagihan.setFieldValue('dataIndex', countJenisTagihan)
						formik.handleSubmit()
					}
				})
			}
		})
	}

	const handleBtnKirim = () => {
		Swal.fire({
			title: 'Apakah data diatas sudah benar semua?',
			text: 'Tagihan yang sudah dikirim tidak bisa diubah kembali',
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: 'Ya, kirim!',
		}).then((result) => {
			if (result.isConfirmed) {
				setKirimLoading(true)
				TagihanSubmit({ ref_id: tagihanID })
					.then((res) => {
						if (res.status == 'ok') {
							setKirimLoading(false)
							Swal.fire({
								title: 'Success',
								text: 'Tagihan berhasil dikirim',
								icon: 'success',
								timer: 2000,
								timerProgressBar: true,
							}).then(() => {
								router.push('/pengajuan-tagihan')
							})
						} else {
							setKirimLoading(false)
						}
					})
					.catch((err) => {
						console.log(err)
						setKirimLoading(false)
					})
			}
		})
	}

	return (
		<>
			<Toast ref={toast} />
			<Head>
				<title>Form Pengajuan Tagihan</title>
			</Head>
			<Belakang>
				<BreadCrumb model={items} home={home} />
				<div className='mb-3'></div>
				<Judul>Form Pengajuan Tagihan</Judul>
				<Card>
					<form onSubmit={formik.handleSubmit}>
						<div className='p-fluid grid grid-cols-2 gap-3'>
							<div className='field col-12 md:col-4'>
								<LabelInput>No SPP</LabelInput>
								<Dropdown
									panelClassName='p-dropdown-form'
									name='no_spp'
									options={optionNoSpp}
									value={formik.values.no_spp}
									onChange={formik.handleChange}
									showClear={formik.values.no_spp ? true : false}
									scrollHeight='200px'
									placeholder='Select No SPP'
									filter
									editable
								/>
								{errorFieldMessage('no_spp')}
							</div>
							<div className='field col-12 md:col-4'>
								<LabelInput>Tanggal SPP</LabelInput>
								<Calendar
									name='tgl_spp'
									value={formik.values.tgl_spp}
									onChange={formik.handleChange}
									showButtonBar
									dateFormat='dd MM yy'
									disabled={countJenisTagihan > 0 ? true : false}
									placeholder='Masukkan tanggal SPP'
									icon='pi pi-calendar'
									showIcon
								/>
								{errorFieldMessage('tgl_spp')}
							</div>
							<div className='field col-12 md:col-4'>
								<LabelInput>Jenis Tagihan</LabelInput>
								<Dropdown
									panelClassName='p-dropdown-form'
									name='jenis_tagihan'
									options={optionJenisTagihan}
									optionLabel='nama'
									optionValue='jenis_id'
									value={formik.values.jenis_tagihan}
									onChange={(e) => {
										formik.setFieldValue('jenis_tagihan', e.value)
										e.value === 'REF-a8be274d-bfe3-4875-b334-2e32bc7e1fca' ? setItsGU(true) : setItsGU(false)
									}}
									showClear={formik.values.jenis_tagihan ? true : false}
									scrollHeight='200px'
									placeholder='Select Jenis Tagihan'
									disabled={countJenisTagihan > 0 ? true : false}
								/>
								{errorFieldMessage('jenis_tagihan')}
							</div>
							<div className='field col-12 md:col-4'>
								<LabelInput>Jenis SPP</LabelInput>
								<InputText disabled value={jenisSPP} />
							</div>
							<div className='field col-12 md:col-4'>
								<LabelInput>Uraian</LabelInput>
								<InputTextarea rows={5} cols={30} value={uraianSPP} disabled />
							</div>
							{itsGU && (
								<div className='field col-12 md:col-4 flex flex-col gap-y-2'>
									<div className='field col-12 md:col-4 flex items-center gap-x-1'>
										<Checkbox
											inputId='ingredient1'
											name='pizza'
											value='Cheese'
											checked={checkedGUGabungan}
											onChange={(e) => {
												setCheckedGUGabungan(e.checked)
												!e.checked && formik.setFieldValue('spp_gabungan', [])
											}}
										/>
										<LabelInput>GU Gabungan</LabelInput>
										<span className='text-xs font-semibold tracking-wide'>*tekan enter pernomor spp</span>
									</div>
									{checkedGUGabungan && (
										<div className=''>
											<LabelInput>No SPP Gabungan</LabelInput>
											<Chips name='spp_gabungan' value={formik.values.spp_gabungan} onChange={formik.handleChange} />
										</div>
									)}
								</div>
							)}
						</div>
					</form>
					<form onSubmit={formikDetailTagihan.handleSubmit}>
						<Accordion activeIndex={0} className='mt-5 accordion-custom'>
							{tagihanList}
						</Accordion>
					</form>
					{countJenisTagihan === 0 && formikDetailTagihan.values.detail_tagihan[countJenisTagihan] === undefined ? (
						<div className='flex justify-end gap-2 mt-3'>
							<Button
								label='Kirim'
								icon={`pi ${kirimLoading ? 'pi-spin pi-spinner' : 'pi-send'}`}
								className='p-button-sm p-button-info'
								onClick={handleBtnKirim}
								disabled={true}
							/>
							<Button
								type='submit'
								label='Tambah Tagihan'
								icon='pi pi-plus'
								className='p-button-sm p-button-primary'
								onClick={handleTambahTagihan}
								disabled={false}
							/>
						</div>
					) : (
						<div className='flex justify-end gap-2 mt-3'>
							<Button
								label='Kirim'
								icon={`pi ${kirimLoading ? 'pi-spin pi-spinner' : 'pi-send'}`}
								className='p-button-sm p-button-info'
								onClick={handleBtnKirim}
								disabled={
									formikDetailTagihan.values.detail_tagihan[countJenisTagihan - 1] !== undefined &&
									formikDetailTagihan.values.detail_tagihan[countJenisTagihan - 1].status === true
										? false
										: true
								}
							/>
							<Button
								type='submit'
								label='Tambah Tagihan'
								icon='pi pi-plus'
								className='p-button-sm p-button-primary'
								onClick={handleTambahTagihan}
								disabled={
									formikDetailTagihan.values.detail_tagihan[countJenisTagihan - 1] !== undefined &&
									formikDetailTagihan.values.detail_tagihan[countJenisTagihan - 1].status === true
										? false
										: true
								}
							/>
						</div>
					)}
				</Card>
			</Belakang>
		</>
	)
}

export const getServerSideProps = async (ctx) => {
	let token = ctx.req.cookies.token

	const optionJenisTagihan = await fetchAPI('jenis-tagihan/list', token)
	const optionJenisBelanja = await fetchAPI('jenis-belanja/list', token)

	return {
		props: {
			optionJenisTagihan,
			optionJenisBelanja,
		},
	}
}
