import { DatatablePrimeV2 } from '@/components/Datatables-v2'
import { Label } from '@/components/Label'
import { Belakang } from '@/components/Layouts'
import { Judul } from '@/components/TextCustom'
import { TagihanDelete, TagihanList } from '@/services/pengajuan-tagihan/tagihan-service'
import { JenisTagihanList } from '@/services/referensi/jenisTagihan-service'
import { Formik } from 'formik'
import moment from 'moment'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { Button } from 'primereact/button'
import { Calendar } from 'primereact/calendar'
import { Card } from 'primereact/card'
import { Column } from 'primereact/column'
import { DataTable } from 'primereact/datatable'
import { Dropdown } from 'primereact/dropdown'
import { InputText } from 'primereact/inputtext'
import { Toast } from 'primereact/toast'
import React, { useEffect, useRef, useState } from 'react'

export default function PengajuanTagihan() {
	const toast = useRef(null)
	const [data, setData] = useState([])
	const [dialogDelete, setDialogDelete] = useState({ visible: false })
	const [expandedRows, setExpandedRows] = useState(null)
	const [ddJenisTagihan, setDdJenisTagihan] = useState([])
	const [search, setSearch] = useState({})
	const router = useRouter()
	const [loading, setLoading] = useState(false)
	const [refresh, setRefresh] = useState(0)

	// DATATABLE
	const [sort, setSort] = useState([])
	const [orderDir, setOrderDir] = useState('desc')
	const [orderCol, setOrderCol] = useState(2)
	const [first, setFirst] = useState(0)
	const [page, setPage] = useState(0)
	const [length, setLength] = useState(10)
	const [totalRecords, setTotalRecords] = useState(0)

	useEffect(() => {
		JenisTagihanList().then((res) => setDdJenisTagihan(res.data))
	}, [])

	useEffect(() => {
		setLoading(true)
		let params = {
			draw: page,
			start: first,
			length: length,
			order_col: orderCol,
			order_dir: orderDir,
		}

		const { no_spp, jenis_tagihan, tanggal_input } = search
		params.no_spp = no_spp ? no_spp : ''
		params.jenis_tagihan = jenis_tagihan ? jenis_tagihan : ''
		params.tanggal_input = tanggal_input ? moment(tanggal_input).format('YYYY-MM-DD') : ''

		TagihanList(params).then((res) => {
			setData(res.data)
			setLoading(false)
			setTotalRecords(
				res.recordsFiltered === 1 ? 1 : res.recordsFiltered < 1 ? res.recordsFiltered : res.recordsFiltered
			)
		})
	}, [page, first, length, orderCol, orderDir, refresh, search])

	const editTagihan = (data) => {
		if (data.tanggal_kirim === '-' && data.detail.length > 0) {
			router.push({ pathname: '/pengajuan-tagihan/draft/[draft]', query: { draft: data.tagihan_id } })
		} else if (data.tanggal_kirim === '-') {
			router.push({ pathname: '/pengajuan-tagihan/force-close/[force]', query: { force: data.tagihan_id } })
		} else {
			router.push({ pathname: '/pengajuan-tagihan/ditolak/[ditolak]', query: { ditolak: data.tagihan_id } })
		}
	}

	const deleteTagihan = () => {
		TagihanDelete({ ref_id: dialogDelete.ref_id }).then((res) => {
			if (res.status === 'success') {
				setRefresh(Math.random)
				setDialogDelete({ visible: false })
				toast.current.show({
					severity: 'success',
					detail: res.message,
					closable: false,
				})
			} else {
				setDialogDelete({ visible: false })
				toast.current.show({
					severity: 'error',
					detail: res.message,
					closable: false,
				})
			}
		})
	}

	const actionBodyTemplate = (rowData) => {
		return (
			<div className='flex gap-x-2'>
				<Button
					icon='pi pi-pencil'
					className='p-button-sm p-button-rounded'
					onClick={() => editTagihan(rowData)}
					disabled={rowData.tanggal_kirim === '-' || rowData.editable || rowData.penolakan ? false : true}
				/>
				<Button
					icon='pi pi-trash'
					className='p-button-sm p-button-rounded p-button-danger'
					onClick={() => setDialogDelete({ ref_id: rowData.tagihan_id, visible: true })}
					disabled={rowData.tanggal_kirim === '-' || rowData.editable ? false : true}
				/>
			</div>
		)
	}

	const bodyTanggal = (rowData) => {
		return rowData.tanggal_spp !== '-' ? (
			moment(rowData.tanggal_spp).format('DD MMMM YYYY')
		) : (
			<Label type={'warning'}>Belum dikirim</Label>
		)
	}

	const datatableDetail = (data) => {
		return (
			<DataTable value={data} className='mx-20'>
				<Column field='akun' header='Akun'></Column>
				<Column field='keperluan' header='Keperluan'></Column>
				<Column field='nomor_tagihan' header='Nomor Tagihan'></Column>
			</DataTable>
		)
	}

	const expandRow = {
		expandedRows: expandedRows,
		onRowToggle: (e) => setExpandedRows(e.data),
		responsiveLayout: 'scroll',
		rowExpansionTemplate: (e) => datatableDetail(e.detail),
		dataKey: 'no_spp',
	}

	const Pencarian = (
		<React.Fragment>
			<Formik
				initialValues={{ no_spp: '', jenis_tagihan: '', tanggal_input: '' }}
				onSubmit={(values) => {
					const tempTanggalInput = values.tanggal_input
					values.tanggal_input &&
						Object.assign(values, { tanggal_input: moment(values.tanggal_input).format('YYYY-MM-D') })
					setSearch(values)
					values.tanggal_input = tempTanggalInput
				}}
			>
				{({ values, handleChange, handleSubmit }) => {
					return (
						<form onSubmit={handleSubmit}>
							<div className='flex gap-x-5 items-center justify-center'>
								<div className='flex flex-col'>
									<label htmlFor='no_spp'>No SPP</label>
									<InputText
										id='no_spp'
										name='no_spp'
										value={values.no_spp}
										onChange={handleChange}
										placeholder='Masukkan Nomor SPP'
									/>
								</div>
								<div className='flex flex-col'>
									<label htmlFor='no_spp'>Jenis Tagihan</label>
									<Dropdown
										name='jenis_tagihan'
										value={values.jenis_tagihan}
										optionValue='jenis_id'
										optionLabel='nama'
										options={ddJenisTagihan}
										onChange={handleChange}
										placeholder='Select Jenis Tagihan'
										showClear={values.jenis_tagihan ? true : false}
										className='w-52'
									/>
								</div>
								<div className='flex flex-col'>
									<label htmlFor='no_spp'>Tanggal Input</label>
									<Calendar
										name='tanggal_input'
										value={values.tanggal_input}
										onChange={handleChange}
										placeholder='e.g. 17 Agustus 1945'
										dateFormat='dd MM yy'
										showButtonBar
									></Calendar>
								</div>
								<div className='flex flex-col'>
									<label htmlFor=''>&nbsp;</label>
									<Button type='submit' label='Cari' className='p-button-sm p-button-success' icon='pi pi-search' />
								</div>
							</div>
						</form>
					)
				}}
			</Formik>
		</React.Fragment>
	)

	const bodyStatus = (rowData) => {
		let status
		if (rowData.tahapan === 6) {
			status = <Label type={'success'}>Selesai</Label>
		} else if (rowData.penolakan === true || rowData.pernah_ditolak === true) {
			status = <Label type={'danger'}>Ditolak/pernah ditolak</Label>
		} else {
			status = '-'
		}
		return status
	}

	const allowExpansion = (rowData) => {
		return rowData.detail.length > 0
	}

	return (
		<>
			<Toast ref={toast} />
			<Head>
				<title>Pengajuan Tagihan</title>
			</Head>
			<Belakang>
				<Judul>Pengajuan Tagihan</Judul>
				<Card className='card-search my-3'>{Pencarian}</Card>
				<div className='flex justify-end mb-3'>
					<Button
						className='p-button-sm'
						label={'Tambah Tagihan'}
						onClick={() => {
							router.push('/pengajuan-tagihan/form')
						}}
					/>
				</div>
				<DatatablePrimeV2
					data={data}
					dialogDelete={dialogDelete}
					setDialogDelete={setDialogDelete}
					deleteTagihan={deleteTagihan}
					first={first}
					length={length}
					loading={loading}
					onSort={(e) => {
						setSort(e.multiSortMeta)
						if (e.multiSortMeta.length > 0) {
							switch (e.multiSortMeta[0].field) {
								case 'no_spp':
									setOrderCol(0)
									break

								case 'nama_tagihan':
									setOrderCol(1)
									break

								case 'tanggal':
									setOrderCol(2)
									break
							}

							switch (e.multiSortMeta[0].order) {
								case -1:
									setOrderDir('desc')
									break

								case 1:
									setOrderDir('asc')
									break
							}
						}
					}}
					setFirst={setFirst}
					setLength={setLength}
					setPage={setPage}
					sort={sort}
					totalRecords={totalRecords}
					page={page}
					expandRow={expandRow}
				>
					<Column expander={allowExpansion} style={{ width: '50px' }} />
					<Column field='no_spp' header='Nomor SPP' sortable></Column>
					<Column field='nama_tagihan' header='Jenis Tagihan' sortable></Column>
					<Column field='tanggal_spp' header='Tanggal SPP' body={bodyTanggal} sortable></Column>
					<Column header='Status' body={bodyStatus}></Column>
					<Column header='Action' body={actionBodyTemplate}></Column>
				</DatatablePrimeV2>
			</Belakang>
		</>
	)
}
