import { DatatablePrimeV2 } from '@/components/Datatables-v2'
import { Belakang } from '@/components/Layouts'
import { Judul } from '@/components/TextCustom'
import { SPMList } from '@/services/otorisasi/spm-service'
import { Formik } from 'formik'
import moment from 'moment'
import Head from 'next/head'
import Link from 'next/link'
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 { InputText } from 'primereact/inputtext'
import { Tag } from 'primereact/tag'
import { Toast } from 'primereact/toast'
import React, { useEffect, useRef, useState } from 'react'

export default function Ppspm() {
	const toast = useRef(null)
	const [data, setData] = useState([])
	const [loading, setLoading] = useState(false)
	const [search, setSearch] = useState({})

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

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

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

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

	const actionBodyTemplate = (rowData) => {
		let all_spp_exist = 'all_spp_exist' in rowData ? rowData.all_spp_exist : true
		if (all_spp_exist) {
			if (rowData.detail.length > 1) {
				if (rowData.nama_tagihan === 'LS') {
					return (
						<div className='flex gap-x-2'>
							{rowData.status === 6 ? (
								<Tag severity='success' value='Done'></Tag>
							) : (
								<Link href={`/otorisasi/spm/form?tagihan_id=${rowData.tagihan_id}`}>
									<Button icon='pi pi-play' label='Proses' className='p-button-sm p-button-rounded' />
								</Link>
							)}
						</div>
					)
				} else {
					return ''
				}
			} else {
				return (
					<div className='flex gap-x-2'>
						{rowData.status === 6 ? (
							<Tag severity='success' value='Done'></Tag>
						) : (
							<Link href={`/otorisasi/spm/form?tagihan_id=${rowData.tagihan_id}`}>
								<Button icon='pi pi-play' label='Proses' className='p-button-sm p-button-rounded' />
							</Link>
						)}
					</div>
				)
			}
		} else {
			return ''
		}
	}

	const actionBodyTemplate2 = (rowData, belomSPM, all_spp_exist) => {
		return (
			rowData && (
				<div className='flex gap-x-2'>
					{rowData.status === 6 ? (
						<Tag severity='success' value='Done'></Tag>
					) : rowData.status < 5 ? (
						<Tag severity='warning' value='On Process'></Tag>
					) : belomSPM || !all_spp_exist ? (
						<Tag severity='warning' value='Waiting Others'></Tag>
					) : (
						<Link href={`/otorisasi/spm/form?tagihan_id=${rowData.tagihan_id}`}>
							<Button icon='pi pi-play' label='Proses' className='p-button-sm p-button-rounded' />
						</Link>
					)}
				</div>
			)
		)
	}

	const datatableDetail = (data, all_spp_exist) => {
		let cekStatus = []
		data.map((val) => {
			cekStatus.push(val.status)
		})
		let belomSPM = cekStatus.find((val) => val < 5)
		return (
			<DataTable value={data} responsiveLayout='scroll' style={{ width: '100%' }} className='dt-detail mx-20'>
				<Column field='no_spp' header='No SPP'></Column>
				<Column
					header='Action/status'
					body={(e) => actionBodyTemplate2(e, belomSPM, all_spp_exist)}
					exportable={false}
				></Column>
			</DataTable>
		)
	}

	const allowExpansion = (rowData) => {
		return rowData.detail.length > 0 && rowData.nama_tagihan === 'GUP'
	}

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

	const Pencarian = (
		<React.Fragment>
			<Formik
				initialValues={{ no_spp: '', 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'>Tanggal Kirim</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 bodyTanggal = (rowData) => {
		return rowData.tanggal_kirim === '-' ? rowData.tanggal_kirim : moment(rowData.tanggal_kirim).format('DD MMMM YYYY')
	}

	return (
		<>
			<Toast ref={toast} />
			<Head>
				<title>PPSPM</title>
			</Head>
			<Belakang>
				<Judul>PPSPM</Judul>
				<Card className='card-search my-3'>{Pencarian}</Card>
				<DatatablePrimeV2
					data={data}
					first={first}
					length={length}
					loading={loading}
					page={page}
					setFirst={setFirst}
					setLength={setLength}
					setPage={setPage}
					totalRecords={totalRecords}
					sort={sort}
					onSort={(e) => {
						setSort(e.multiSortMeta)
						if (e.multiSortMeta.length > 0) {
							switch (e.multiSortMeta[0].field) {
								case 'no_spp':
									setOrderCol(0)
									break

								case 'tanggal':
									setOrderCol(3)
									break
							}

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

								case 1:
									setOrderDir('asc')
									break
							}
						}
					}}
					expandRow={expandRow}
				>
					<Column expander={allowExpansion} />
					<Column field='no_spp' header='Nomor SPP' sortable></Column>
					<Column field='nama_tagihan' header='Nama Tagihan'></Column>
					<Column field='spp_gabungan' header='SPP Gabungan'></Column>
					<Column field='tanggal' header='Tanggal Kirim' body={bodyTanggal} sortable></Column>
					<Column header='Action/status' body={actionBodyTemplate} exportable={false}></Column>
				</DatatablePrimeV2>
			</Belakang>
		</>
	)
}
