import { DatatablePrimeV2 } from '@/components/Datatables-v2'
import { Belakang } from '@/components/Layouts'
import { Judul } from '@/components/TextCustom'
import { DashboardAll, DashboardP2k } from '@/services/dashboard-service'
import { JenisTagihanList } from '@/services/referensi/jenisTagihan-service'
import { Formik } from 'formik'
import moment from 'moment'
import Head from 'next/head'
import { Button } from 'primereact/button'
import { Calendar } from 'primereact/calendar'
import { Card } from 'primereact/card'
import { Column } from 'primereact/column'
import { Dropdown } from 'primereact/dropdown'
import { InputText } from 'primereact/inputtext'
import React, { useEffect, useState } from 'react'

export default function Dashboard() {
	const [data, setData] = useState([])
	const [displayDialog, setDisplayDialog] = useState(false)
	const [dataDialog, setDataDialog] = useState([])
	const [search, setSearch] = useState({})
	const [ddJenisTagihan, setDdJenisTagihan] = useState([])

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

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

	useEffect(() => {
		const { role } = JSON.parse(localStorage.getItem('user'))
		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') : ''

		if (role === 'PPK' || role === 'Verifikator') {
			DashboardP2k(params).then((res) => {
				setLoading(false)
				setData(res.data)
				setTotalRecords(res.recordsFiltered - 1)
			})
		} else {
			DashboardAll(params).then((res) => {
				setLoading(false)
				setData(res.data)
				setTotalRecords(res.recordsFiltered - 1)
			})
		}
	}, [page, first, length, orderCol, orderDir, search])

	const bodyDetail = (rowData) => {
		return (
			<div className='flex gap-x-2'>
				<Button
					label='Detail'
					className='p-button-sm'
					onClick={() => {
						setDisplayDialog(true), setDataDialog(rowData)
					}}
				/>
			</div>
		)
	}

	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>
	)

	return (
		<React.Fragment>
			<Head>
				<title>Dashboard</title>
			</Head>
			<Belakang>
				<Judul>Data Transaction</Judul>
				<Card className='card-search my-3'>{Pencarian}</Card>
				<DatatablePrimeV2
					data={data}
					first={first}
					loading={loading}
					setFirst={setFirst}
					setLength={setLength}
					setPage={setPage}
					sort={sort}
					totalRecords={totalRecords}
					length={length}
					onSort={(e) => {
						setSort(e.multiSortMeta)
						console.log('sorting', e)
						if (e.multiSortMeta.length > 0) {
							switch (e.multiSortMeta[0].field) {
								case 'no_spp':
									setOrderCol(0)
									break

								case 'nama_unit':
									setOrderCol(1)
									break

								case 'tanggal':
									setOrderCol(2)
									break
							}

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

								case 1:
									setOrderDir('asc')
									break
							}
						}
					}}
					dataDialog={dataDialog}
					displayDialog={displayDialog}
					setDisplayDialog={setDisplayDialog}
				>
					<Column field='no_spp' header='Nomor SPP' sortable></Column>
					<Column field='nama_unit' header='Unit PPK' sortable></Column>
					<Column field='tanggal_kirim' header='Tanggal Pengajuan' sortable></Column>
					<Column field='status_tagihan' header='Status'></Column>
					<Column field='no_spm' header='No SPM'></Column>
					<Column field='no_sp2d' header='No SP2D'></Column>
					<Column field='tgl_spm' header='Tanggal SPM'></Column>
					<Column field='tgl_sp2d' header='Tanggal SP2D'></Column>
					<Column header='Detail' body={bodyDetail}></Column>
				</DatatablePrimeV2>
			</Belakang>
		</React.Fragment>
	)
}
