import { CardCustom } from '@/components/CardCustom'
import { Belakang } from '@/components/Layouts'
import { Judul, SubJudul } from '@/components/TextCustom'
import { TagihanGetOne, TagihanSubmit } from '@/services/pengajuan-tagihan/tagihan-service'
import { Formik } from 'formik'
import Head from 'next/head'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { Accordion, AccordionTab } from 'primereact/accordion'
import { Button } from 'primereact/button'
import { Card } from 'primereact/card'
import { FileUpload } from 'primereact/fileupload'
import { InputTextarea } from 'primereact/inputtextarea'
import { ProgressBar } from 'primereact/progressbar'
import { TabPanel, TabView } from 'primereact/tabview'
import { Toast } from 'primereact/toast'
import React, { useEffect, useRef, useState } from 'react'
import Swal from 'sweetalert2'
import axios from '../../../lib/axios'

export default function Ditolak() {
	const router = useRouter()
	const [data, setData] = useState([])
	const toast = useRef(null)
	const [progressUpload, setProgressUpload] = useState(0)

	useEffect(() => {
		TagihanGetOne({ ref_id: router.query.ditolak }).then((res) => {
			if (res.status === 'ok') {
				setData(res.data)
			} else {
				console.log(res.message)
			}
		})
	}, [router])

	const formikInitialValues = () => {
		let groupTagihan = []
		let detailIDTolak = []
		data.length > 0 &&
			data[1].map((valData) => {
				valData.syarat.map((valSyarat) => {
					if (valSyarat.ms === 'tms') {
						let cek_detail_id = detailIDTolak.find((e) => e === valData.detail_id)
						!cek_detail_id && detailIDTolak.push(valData.detail_id)
					}
				})
			})

		detailIDTolak.map((valDetailIDTolak, iDetailIDTolak) => {
			data.length > 0 &&
				data[1]
					.filter((valTagihan) => valTagihan.detail_id === detailIDTolak[iDetailIDTolak])
					.map((valData) => {
						groupTagihan.push({
							detail_id: valData.detail_id,
							jenis_belanja: valData.jenis_belanja,
							jenis_kegiatan: valData.jenis_kegiatan,
							syarat: valData.syarat.map((valSyarat) => {
								if (valSyarat.ms === 'tms') {
									return {
										syarat_id: valSyarat.syarat_id,
										syarat_dokumen: valSyarat.syarat_dokumen,
										keterangan: valSyarat.keterangan,
										file: '',
										file_name: '',
										ms: valSyarat.ms,
										verif_note: valSyarat.verif_note,
										kasub_note: valSyarat.kasub_note,
										kabag_note: valSyarat.kabag_note,
										bendahara_note: valSyarat.bendahara_note,
										spm_note: valSyarat.spm_note,
									}
								}
							}),
							akun_id: valData.akun_id,
							filepath_old: valData.filepath,
							keperluan: valData.keperluan,
							draft: false,
						})
					})
		})

		return {
			tagihan_id: data[0].tagihan_id,
			detail_tagihan: groupTagihan,
		}
	}

	return (
		<React.Fragment>
			<Toast ref={toast} />
			<Head>
				<title>Pengajuan Tagihan Ulang</title>
			</Head>
			<Belakang>
				{data.length > 0 && (
					<React.Fragment>
						<div className='mb-5'></div>
						<Judul>Form Pengajuan Tagihan Ulang</Judul>
						<Card>
							<div className='grid grid-cols-2 gap-3'>
								<CardCustom header={'No SPP'} content={data[0].no_spp} />
								<CardCustom header={'Unit PPK'} content={data[0].unit} />
								<CardCustom header={'Jenis Tagihan'} content={data[0].tagihan} />
							</div>
						</Card>
						<Formik
							initialValues={formikInitialValues()}
							onSubmit={(values, { setSubmitting }) => {
								setSubmitting(true)
								TagihanSubmit({ ref_id: data[0].tagihan_id })
									.then((res) => {
										if (res.status === 'ok') {
											Swal.fire({
												title: 'Success',
												text: 'Tagihan berhasil dikirim',
												icon: 'success',
												timer: 2000,
												timerProgressBar: true,
											}).then(() => {
												setSubmitting(false)
												router.push('/pengajuan-tagihan')
											})
										}
									})
									.catch((err) => {
										setSubmitting(false)
										console.log(err)
									})
							}}
							validate={(data) => {
								let errors = {}
								data.detail_tagihan.map((val) => {
									if (!val.file) {
										toast.current.show({
											severity: 'error',
											detail: 'file belum diupload',
											closable: false,
										})
										errors.filepath = val
									}
								})

								return errors
							}}
							validateOnChange={false}
						>
							{({ values, setFieldValue, handleSubmit, isSubmitting }) => {
								const handleRevisi = () => {
									handleSubmit()
								}
								return (
									<React.Fragment>
										<Accordion className='mt-3 shadow'>
											{values.detail_tagihan.map((valDetailTagihan, indexDetailTagihan) => {
												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 = async function () {
																const base64data = reader.result
																setFieldValue(`detail_tagihan[${indexDetailTagihan}].file`, base64data)
																setFieldValue(`detail_tagihan[${indexDetailTagihan}].file_name`, file.name)

																const kirimSatuan = {
																	detail_id: valDetailTagihan.detail_id,
																	file: base64data,
																	file_name: file.name,
																}

																await axios
																	.post('tagihan/revisi_detail', kirimSatuan, {
																		headers: {
																			'Content-Type': 'application/json',
																		},
																		onUploadProgress: (progresEvent) => {
																			const percentedCompleted = Math.round(
																				(progresEvent.loaded * 100) / progresEvent.total
																			)
																			setProgressUpload(percentedCompleted)
																		},
																	})
																	.then(() => {
																		toast.current.show({
																			severity: 'success',
																			detail: 'File berhasil diupload',
																			closable: false,
																		})
																	})
																	.catch((err) => console.log(err))
															}
														} else {
															event.options.clear()
															toast.current.show({
																severity: 'error',
																detail: 'Invalid format file',
																closable: false,
															})
															setFieldValue(`detail_tagihan[${indexDetailTagihan}].file`, null)
															setFieldValue(`detail_tagihan[${indexDetailTagihan}].file_name`, null)
														}
													}
												}
												return (
													<AccordionTab
														header={`Tagihan ` + (parseInt(indexDetailTagihan) + 1)}
														key={indexDetailTagihan}
													>
														<div className='grid grid-cols-2 gap-3'>
															<CardCustom
																header={'Jenis Belanja'}
																content={valDetailTagihan.jenis_belanja}
																type='cream'
															/>
															<CardCustom
																header={'Jenis Kegiatan'}
																content={valDetailTagihan.jenis_kegiatan}
																type='cream'
															/>
															<CardCustom header={'Akun'} content={valDetailTagihan.akun_id} type='cream' />
															<CardCustom
																header={'Keperluan Untuk'}
																content={valDetailTagihan.keperluan}
																type='cream'
															/>
														</div>
														<div className='my-3'>
															<SubJudul className='text-lg mb-1'>Syarat</SubJudul>
															<Accordion className='accordion-syarat'>
																{valDetailTagihan.syarat.map((valSyarat, indexSyarat) => {
																	if (valSyarat) {
																		return (
																			<AccordionTab
																				header={valSyarat.syarat_dokumen}
																				key={indexSyarat}
																				headerClassName='accordiontab-revisi'
																			>
																				<table className='custom-table' key={indexSyarat}>
																					<tbody>
																						<tr className=''>
																							<td colSpan={4}>
																								<p className='text-xl font-semibold mb-1'>Catatan</p>
																								<TabView key={indexSyarat}>
																									<TabPanel header='Catatan Verif'>
																										<InputTextarea
																											rows={5}
																											cols={30}
																											value={valSyarat.verif_note ? valSyarat.verif_note : ''}
																											className='w-full'
																											readOnly
																										/>
																									</TabPanel>
																									<TabPanel header='Catatan Bendahara'>
																										<InputTextarea
																											rows={5}
																											cols={30}
																											value={valSyarat.bendahara_note ? valSyarat.bendahara_note : ''}
																											className='w-full'
																											readOnly
																										/>
																									</TabPanel>
																									<TabPanel header='Catatan SPM'>
																										<InputTextarea
																											rows={5}
																											cols={30}
																											value={valSyarat.spm_note ? valSyarat.spm_note : ''}
																											className='w-full'
																											readOnly
																										/>
																									</TabPanel>
																								</TabView>
																							</td>
																						</tr>
																					</tbody>
																				</table>
																			</AccordionTab>
																		)
																	}
																})}
															</Accordion>
														</div>
														<div className='my-3'>
															<table className='custom-table'>
																<thead>
																	<tr>
																		<th>File Sebelum</th>
																		<th>Upload File Revisi</th>
																	</tr>
																</thead>
																<tbody>
																	<tr>
																		<td className='text-center'>
																			<Link href={process.env.NEXT_PUBLIC_BACKEND_API + valDetailTagihan.filepath_old}>
																				<a target={'_blank'} className='flex items-center justify-center gap-x-1'>
																					<i className='pi pi-file-pdf' style={{ fontSize: '2em' }} />
																					<p className='text-sm hover:underline'>Klik disini untuk lihat file</p>
																				</a>
																			</Link>
																		</td>
																		<td>
																			<FileUpload
																				name='upload-syarat'
																				url={'#'}
																				accept='.pdf'
																				emptyTemplate={<p className='m-0'>Drag and drop files to here to upload.</p>}
																				customUpload
																				uploadHandler={(e) => customBase64Uploader(e)}
																				onClear={() =>
																					setFieldValue(`detail_tagihan[${indexDetailTagihan}].file`, false)
																				}
																				onRemove={() =>
																					setFieldValue(`detail_tagihan[${indexDetailTagihan}].file`, false)
																				}
																				uploadOptions={{
																					className: values.detail_tagihan[indexDetailTagihan].file ? 'p-disabled' : '',
																				}}
																				cancelOptions={{
																					className: values.detail_tagihan[indexDetailTagihan].file ? 'p-disabled' : '',
																				}}
																				progressBarTemplate={
																					<ProgressBar
																						value={progressUpload}
																						style={{ height: '1rem', fontSize: '13px' }}
																					></ProgressBar>
																				}
																			/>
																		</td>
																	</tr>
																</tbody>
															</table>
														</div>
													</AccordionTab>
												)
											})}
										</Accordion>
										<div className='mt-3 flex justify-center gap-x-3'>
											<Button
												type='submit'
												label='Kirim'
												onClick={() => handleRevisi()}
												className='p-button-sm'
												loading={isSubmitting}
											/>
										</div>
									</React.Fragment>
								)
							}}
						</Formik>
					</React.Fragment>
				)}
			</Belakang>
		</React.Fragment>
	)
}
