import { RoleCreate, RoleUpdate } from '@/services/manajemen/role-service'
import { useFormik } from 'formik'
import { Button } from 'primereact/button'
import { Dialog } from 'primereact/dialog'
import { InputText } from 'primereact/inputtext'
import { Tree } from 'primereact/tree'

export default function FormRole({ dialogForm, setDialogForm, dataEdit, setDataEdit, refresh, toast }) {
	const formik = useFormik({
		initialValues: {
			role_id: dataEdit.role_id || '',
			nama: dataEdit.nama || '',
			access: dataEdit.access || [],
		},
		validate: (data) => {
			let errors = {}
			if (!data.nama) errors.nama = 'Nama is required.'
			if (!data.access) errors.access = 'Nama is required.'
			return errors
		},
		onSubmit: (data) => {
			Object.assign(data, { access: JSON.stringify(data.access) })
			if (data.role_id) {
				RoleUpdate(data).then((res) => {
					if (res.status === 'success') {
						refresh(Math.random)
						formik.resetForm()
						setDataEdit([])
						setDialogForm(false)
						toast.current.show({
							severity: 'success',
							detail: res.message,
							closable: false,
						})
					} else {
						setDialogForm(false)
						toast.current.show({
							severity: 'error',
							detail: res.message,
							closable: false,
						})
					}
				})
			} else {
				RoleCreate(data).then((res) => {
					if (res.status === 'success') {
						refresh(Math.random)
						formik.resetForm()
						setDataEdit([])
						setDialogForm(false)
						toast.current.show({
							severity: 'success',
							detail: res.message,
							closable: false,
						})
					} else {
						setDialogForm(false)
						toast.current.show({
							severity: 'error',
							detail: res.message,
							closable: false,
						})
					}
				})
			}
		},
	})

	const isFieldValid = (field) => !!(formik.touched[field] && formik.errors[field])
	const errorFieldMessage = (field) => {
		return (
			isFieldValid(field) && (
				<small className='p-error' style={{ fontSize: '11px' }}>
					{formik.errors[field]}
				</small>
			)
		)
	}

	const dialogFooter = (
		<div className='flex justify-end'>
			<Button
				type='submit'
				label='Cancel'
				className='p-button-sm p-button-secondary'
				onClick={() => {
					formik.resetForm()
					setDialogForm(false)
				}}
			/>
			<Button type='submit' label='Save' className='p-button-sm p-button-primary' onClick={formik.handleSubmit} />
		</div>
	)

	const data = [
		{
			key: 'dashboard',
			label: 'Dashboard',
			icon: 'pi pi-fw pi-home',
		},
		{
			key: 'referensi',
			label: 'Referensi',
			icon: 'pi pi-fw pi-database',
			children: [
				{ key: 'referensi/jenis-tagihan', label: 'Jenis Tagihan' },
				{ key: 'referensi/jenis-belanja', label: 'Jenis Belanja' },
				{ key: 'referensi/jenis-kegiatan', label: 'Jenis Kegiatan' },
				{ key: 'referensi/akun', label: 'Akun' },
				{ key: 'referensi/persyaratan', label: 'Persyaratan' },
				{ key: 'referensi/unit-kerja', label: 'Unit Kerja' },
				{ key: 'referensi/verifikator', label: 'Verifikator' },
			],
		},
		{
			key: 'pengajuan-tagihan',
			label: 'Pengajuan Tagihan',
			icon: 'pi pi-fw pi-dollar',
		},
		{
			key: 'laporan',
			label: 'Laporan',
			icon: 'pi pi-fw pi-chart-line',
			children: [
				{ key: 'laporan/per-user', label: 'Per User (Verifikator, kasub verif)' },
				// { key: 'laporan/approval', label: 'Approval (Kabag verif, bendahara, ppspm)' },
				{ key: 'laporan/rekap-bulanan-per-user', label: 'Rekapitulasi bulanan per user' },
				{ key: 'laporan/rekap-verif-per-bulan', label: 'Rekapitulasi hasil verifikasi per bulan' },
				{ key: 'laporan/rekap-per-unit-kerja', label: 'Rekapitulasi per unit kerja' },
				{ key: 'laporan/rekap-per-jenis-belanja', label: 'Rekapitulasi per jenis belanja (BAS)' },
				{ key: 'laporan/verif-per-bulan', label: 'Hasil verifikasi per bulan (detail)' },
				{
					key: 'laporan/pengendalian-waktu-penyelesaian',
					label: 'Pengendalian waktu penyelesaian tagihan per unit per bulan',
				},
				{
					key: 'laporan/pengendalian-waktu-penyelesaian-detail',
					label: 'Pengendalian waktu penyelesaian tagihan per unit per bulan (detail)',
				},
			],
		},
		{
			key: 'otorisasi',
			label: 'Otorisasi',
			icon: 'pi pi-fw pi-lock',
			children: [
				{ key: 'otorisasi/verifikasi', label: 'verifikasi' },
				{ key: 'otorisasi/rekomendasi', label: 'rekomendasi' },
				{ key: 'otorisasi/persetujuan', label: 'persetujuan' },
				{ key: 'otorisasi/pengesahan', label: 'pengesahan' },
				{ key: 'otorisasi/spm', label: 'spm' },
			],
		},
		{
			key: 'manajemen',
			label: 'Manajemen',
			icon: 'pi pi-fw pi-database',
			children: [
				{ key: 'manajemen/user', label: 'user' },
				{ key: 'manajemen/role', label: 'role' },
				{ key: 'manajemen/jam-kerja', label: 'jam kerja' },
			],
		},
	]

	return (
		<>
			<Dialog
				header={formik.values.role_id ? 'Update Role' : 'Add Role'}
				className='p-dialog-form'
				visible={dialogForm}
				draggable={false}
				resizable={false}
				position={'center'}
				closable={false}
				style={{ width: '60vw' }}
				footer={dialogFooter}
			>
				<form onSubmit={formik.handleSubmit}>
					<div className='grid grid-cols-2 gap-x-3'>
						{/* KIRI */}
						<div className='kiri'>
							<div className='p-fluid grid'>
								<div className='field col-12 md:col-12 mb-0'>
									<label className='block'>List menu</label>
									<Tree
										name='access'
										value={data}
										selectionMode='checkbox'
										selectionKeys={formik.values.access}
										onSelectionChange={(e) => {
											formik.setFieldValue('access', e.value)
										}}
									/>
								</div>
							</div>
						</div>

						{/* KANAN */}
						<div className='kanan'>
							<div className='p-fluid grid'>
								<div className='field col-12 md:col-12 mb-0'>
									<label className='block'>Nama Role</label>
									<InputText
										className='p-inputtext-sm'
										name='nama'
										value={formik.values.nama}
										onChange={formik.handleChange}
										placeholder='Masukkan nama role'
									/>
									{errorFieldMessage('nama')}
								</div>
							</div>
						</div>
					</div>
				</form>
			</Dialog>
		</>
	)
}
