import { Belakang } from '@/components/Layouts'
import { Judul, LabelInput } from '@/components/TextCustom'
import { DetailSPPGet, NoSPPListGet } from '@/services/pengajuan-tagihan/integrasi-service'
import { TagihanAddDetail, TagihanGetOne, 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 { Formik } from 'formik'
import { fetchAPI } from 'lib/fetch'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { Accordion, AccordionTab } from 'primereact/accordion'
import { BlockUI } from 'primereact/blockui'
import { Button } from 'primereact/button'
import { Card } from 'primereact/card'
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 React, { useEffect, useRef, useState } from 'react'
import Swal from 'sweetalert2'

export default function ForceClose({ optionJenisTagihan = null, optionJenisBelanja = null }) {
	const router = useRouter()
	const [data, setData] = useState([{ no_spp: '', tgl_spp: '', jenis_tagihan: '' }])
	const toast = useRef(null)
	const [countJenisTagihan, setCountJenisTagihan] = useState(0)
	const [optionJenisKegiatan, setOptionJenisKegiatan] = useState([])
	const [optionNoSpp, setOptionNoSpp] = useState([])
	const [optionAkun, setOptionAkun] = useState([])
	const [statusDraft, setStatusDraft] = useState(false)
	const [kirimLoading, setKirimLoading] = useState(false)

	useEffect(() => {
		TagihanGetOne({ ref_id: router.query.force }).then((res) => {
			if (res.status === 'ok') {
				setData(res.data)
				DetailSPPGet({ no_spp: res.data[0].no_spp }).then((res) => {
					if (res.data.akun.length > 0) {
						setOptionAkun(res.data.akun)
					} else {
						let params = {}
						params.draw = 0
						AkunList(params).then((res) => {
							setOptionAkun(res.data)
						})
					}
				})
			} else {
				console.log(res.message)
			}
		})

		NoSPPListGet()
			.then((res) => setOptionNoSpp(res.data))
			.catch((err) => console.log(err))
	}, [router])

	return (
		<React.Fragment>
			<Toast ref={toast} />
			<Head>
				<title>Pengajuan Tagihan Ulang</title>
			</Head>
			<Belakang>
				<Judul>Form Pengajuan Tagihan</Judul>
				<Card>
					<Formik
						initialValues={{}}
						onSubmit={() => {
							setCountJenisTagihan(countJenisTagihan + 1)
						}}
					>
						{({ handleSubmit, setFieldValue }) => {
							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: data[0].tagihan_id })
											.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)
											})
									}
								})
							}

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

								Swal.fire({
									title: 'Apakah data yang diinputkan sudah benar benar?',
									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) {
												setFieldValue('dataIndex', countJenisTagihan)
												handleSubmit()
											}
										})
									}
								})
							}

							return (
								<React.Fragment>
									<div className='p-fluid grid grid-cols-2 gap-3'>
										<div className='field col-12 md:col-4'>
											<LabelInput>No SPP</LabelInput>
											<InputText disabled value={data[0].no_spp} />
										</div>
										<div className='field col-12 md:col-4'>
											<LabelInput>Tanggal SPP</LabelInput>
											<InputText disabled value={data[0].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={data[0].jenis_tagihan_id}
												placeholder='Select Jenis Tagihan'
												disabled={true}
											/>
										</div>
										<div className='field col-12 md:col-4'>
											<LabelInput>Jenis SPP</LabelInput>
											<InputText disabled value='' />
										</div>
										<div className='field col-12 md:col-4'>
											<LabelInput>Uraian</LabelInput>
											<InputTextarea rows={5} cols={30} value='' disabled />
										</div>
									</div>

									{/* DETAIL TAGIHAN */}
									<Formik
										initialValues={{
											tagihan_id: '',
											detail_tagihan: [],
											dataIndex: 0, //* For select data index
										}}
										onSubmit={(data_detail_tagihan) => {
											/**
											 * *Filter data detail tagihan follow the button kirim
											 */
											const filterData = data_detail_tagihan.detail_tagihan.find(
												(item, i) => i === data_detail_tagihan.dataIndex
											)

											/**
											 * *Create new format data detail tagihan reference to API
											 */
											const dataKirim = {
												tagihan_id: data[0].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
														 */
														setFieldValue('detail_tagihan[' + data.dataIndex + '].status', true)
													} 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
														 */
														setFieldValue('detail_tagihan[' + data.dataIndex + '].status', 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
													 */
													setFieldValue('detail_tagihan[' + data.dataIndex + '].status', false)
												})
										}}
										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
										}}
										validateOnChange={false}
									>
										{({ values, handleChange, handleSubmit, setFieldValue, setValues, errors }) => {
											/**
											 * *Message error for formik detail tagihan
											 */
											const isFieldValidDetail = (index, field) =>
												errors[0] && errors[0].dataIndex === index && errors[0].errors[field]
											const errorFieldMessageDetail = (index, field) => {
												return (
													isFieldValidDetail(index, field) && (
														<small className='p-error' style={{ fontSize: '11px' }}>
															{errors[0].errors[field]}
														</small>
													)
												)
											}

											/**
											 * *Dropdown list jenis kegiatan
											 * *When jenis kegiatan change hit API to get list syarat
											 */
											const changeJenisKegiatan = (event, index) => {
												setFieldValue(`detail_tagihan[${index}].syarat`, [])
												setFieldValue(`detail_tagihan[${index}].jenis_kegiatan`, event.value)
												PersyaratanSearch({
													jenis_tagihan_id: data[0].jenis_tagihan_id,
													jenis_belanja_id: values.detail_tagihan[index].jenis_belanja,
													jenis_kegiatan_id: event.value,
												})
													.then((res) => {
														if (res.data) {
															res.data.map((item, index2) => {
																setFieldValue(`detail_tagihan[${index}].syarat[${index2}].syarat_id`, item.syarat_id)
																setFieldValue(
																	`detail_tagihan[${index}].syarat[${index2}].syarat_dokumen`,
																	item.syarat_dokumen
																)
																setFieldValue(`detail_tagihan[${index}].syarat[${index2}].keterangan`, item.keterangan)
															})
														} else {
															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) => {
												setFieldValue(`detail_tagihan[${index}].syarat`, [])
												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))
											}

											const headerTemplate = (index) => {
												const handleDelete = (index) => {
													setValues({
														values,
														detail_tagihan: 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>
												)
											}

											/**
											 * *Form Detail Tagihan
											 * *Button Submit and draft
											 */
											const handleSubmitDetailTagihan = (e, { draft, index }) => {
												e.preventDefault()
												setStatusDraft(draft)
												setFieldValue(`detail_tagihan[${index}].draft`, draft)
												setFieldValue(`detail_tagihan[${index}].status`, true)
												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
																setFieldValue(`detail_tagihan[${index}].file`, base64data)
																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,
															})
															setFieldValue(`detail_tagihan[${index}].file`, null)
															setFieldValue(`detail_tagihan[${index}].file_name`, null)
														}
													}
												}

												return (
													<AccordionTab
														key={index}
														headerTemplate={headerTemplate(index)}
														className={`accordion-tab-${index}`}
													>
														<BlockUI
															blocked={
																values.detail_tagihan[index] !== undefined && 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={
																			values.detail_tagihan[index] !== undefined
																				? values.detail_tagihan[index].jenis_belanja
																				: setFieldValue(`detail_tagihan[${index}].jenis_belanja`, '')
																		}
																		onChange={(e) => changeJenisBelanja(e, index)}
																		showClear={values.detail_tagihan[index] !== undefined ? true : false}
																		scrollHeight='200px'
																		placeholder='Select Jenis Belanja'
																		className={`${errorFieldMessageDetail(index, 'jenis_belanja') && 'p-invalid'}`}
																	/>
																	{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={
																			values.detail_tagihan[index] !== undefined
																				? values.detail_tagihan[index].jenis_kegiatan
																				: setFieldValue(`detail_tagihan[${index}].jenis_kegiatan`, '')
																		}
																		onChange={(e) => changeJenisKegiatan(e, index)}
																		showClear={values.detail_tagihan[index] !== undefined ? true : false}
																		scrollHeight='200px'
																		placeholder='Select Jenis Kegiatan'
																		filter
																		className={`${errorFieldMessageDetail(index, 'jenis_kegiatan') && 'p-invalid'}`}
																	/>
																	{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>
																				{values.detail_tagihan[index] &&
																					values.detail_tagihan[index].syarat &&
																					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={() => setFieldValue(`detail_tagihan[${index}].file`, false)}
																			onRemove={() => setFieldValue(`detail_tagihan[${index}].file`, false)}
																		/>
																	</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}
																			value={
																				values.detail_tagihan[index] !== undefined
																					? values.detail_tagihan[index].akun_id
																					: setFieldValue(`detail_tagihan[${index}].akun_id`, '')
																			}
																			onChange={handleChange}
																			showClear={values.detail_tagihan[index] !== undefined ? true : false}
																			scrollHeight='300px'
																			placeholder='Select Akun'
																			filter
																			maxLength={100}
																			className={`${errorFieldMessageDetail(index, 'akun') && 'p-invalid'}`}
																		/>
																		{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={
																				values.detail_tagihan[index] !== undefined
																					? values.detail_tagihan[index].akun_id
																					: setFieldValue(`detail_tagihan[${index}].akun_id`, '')
																			}
																			onChange={handleChange}
																			showClear={values.detail_tagihan[index] !== undefined ? true : false}
																			scrollHeight='300px'
																			placeholder='Select Akun'
																			filter
																			maxLength={100}
																			className={`${errorFieldMessageDetail(index, 'akun') && 'p-invalid'}`}
																		/>
																		{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={
																			values.detail_tagihan[index] !== undefined
																				? values.detail_tagihan[index].keperluan
																				: ''
																		}
																		onChange={handleChange}
																		placeholder='Masukkan detail keperluan'
																	/>
																</div>
															</div>
														</BlockUI>

														{/* BUTTON DRAFT, SIMPAN AND MESSAGE */}
														<div className='flex justify-center gap-2 mt-3'>
															{values.detail_tagihan[index] !== undefined &&
															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 })}
																	/>
																	<Button
																		type='submit'
																		label='Simpan'
																		icon='pi pi-send'
																		className='p-button-sm p-button-success'
																		onClick={(e) => handleSubmitDetailTagihan(e, { draft: false, index })}
																	/>
																</>
															)}
														</div>
													</AccordionTab>
												)
											}
											for (let index = 0; index < countJenisTagihan; index++) {
												tagihanList.push(tagihan(index))
											}

											return (
												<React.Fragment>
													<form onSubmit={handleSubmit}>
														<Accordion activeIndex={0} className='mt-5 accordion-custom'>
															{tagihanList}
														</Accordion>
													</form>
													{countJenisTagihan === 0 ? (
														<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={
																	values.detail_tagihan[countJenisTagihan - 1] !== undefined &&
																	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={
																	values.detail_tagihan[countJenisTagihan - 1] !== undefined &&
																	values.detail_tagihan[countJenisTagihan - 1].status === true
																		? false
																		: true
																}
															/>
														</div>
													)}
												</React.Fragment>
											)
										}}
									</Formik>
								</React.Fragment>
							)
						}}
					</Formik>
				</Card>
			</Belakang>
		</React.Fragment>
	)
}

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,
		},
	}
}
