import { RoleList } from '@/services/manajemen/role-service'
import { UserCreate, UserUpdate } from '@/services/manajemen/user-service'
import { UnitKerjaList } from '@/services/referensi/unitKerja-service'
import { useFormik } from 'formik'
import { Button } from 'primereact/button'
import { Dialog } from 'primereact/dialog'
import { Dropdown } from 'primereact/dropdown'
import { InputText } from 'primereact/inputtext'
import { Password } from 'primereact/password'
import { useEffect, useState } from 'react'
import * as Yup from 'yup'

export default function FormUser({ dialogForm, setDialogForm, dataEdit, setDataEdit, refresh, toast }) {
	const [optionUnitKerja, setOptionUnitKerja] = useState([])
	const [optionRole, setOptionRole] = useState([])
	const [showUnitKerja, setShowUnitKerja] = useState(true)

	const SignupSchema = Yup.object().shape({
		name: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Nama is required'),
		username: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Username is required'),
		email: Yup.string().email('Invalid email').required('Email is Required'),
		password: Yup.string().when('old_password', {
			is: true,
			then: Yup.string()
				.required('Password is required')
				.matches(
					/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#%&])(?=.{8,})/,
					'Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character'
				),
		}),
		password_retype: Yup.string().when('old_password', {
			is: true,
			then: Yup.string()
				.oneOf([Yup.ref('password'), null], 'Passwords must match')
				.required('Password confirm is required'),
		}),
		// unit: Yup.string().required('Unit kerja is required'),
		role: Yup.string().required('Role is required'),
	})

	const formik = useFormik({
		initialValues: {
			user_id: dataEdit.user_id || '',
			name: dataEdit.nama || '',
			username: dataEdit.username || '',
			email: dataEdit.email || '',
			password: '',
			password_retype: '',
			unit: dataEdit.unit || '',
			role: dataEdit.user_role || '',
		},
		validationSchema: SignupSchema,
		onSubmit: (data) => {
			if (data.user_id) {
				UserUpdate(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 {
				UserCreate(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,
						})
					}
				})
			}
		},
	})

	useEffect(() => {
		UnitKerjaList({ draw: 0 }).then((res) => setOptionUnitKerja(res.data))
		RoleList().then((res) => setOptionRole(res.data))
	}, [])

	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 header = <h6>Pick a password</h6>
	const footer = (
		<>
			<p className='mt-3'>Suggestions</p>
			<ul className='pl-2 ml-2 mt-0' style={{ lineHeight: '1.5' }}>
				<li>At least one lowercase</li>
				<li>At least one uppercase</li>
				<li>At least one numeric</li>
				<li>At least one special case character</li>
				<li>Minimum 8 characters</li>
				<li>If edit password not required</li>
			</ul>
		</>
	)

	const handleRole = (e) => {
		if (e.target.value === 'ROL-a713f345-9b9a-453a-8f77-33fd8335078f') {
			setShowUnitKerja(false)
		} else {
			setShowUnitKerja(true)
		}

		formik.setFieldValue('role', e.target.value)
	}

	return (
		<>
			<Dialog
				header={formik.values.user_id ? 'Update User' : 'Add User'}
				className='p-dialog-form'
				visible={dialogForm}
				draggable={false}
				resizable={false}
				position={'center'}
				closable={false}
				style={{ width: '30vw' }}
				footer={dialogFooter}
			>
				<form onSubmit={formik.handleSubmit}>
					<div className='kanan'>
						<div className='p-fluid grid'>
							<div className='field col-12 md:col-12 mb-2'>
								<label className='block'>Nama</label>
								<InputText
									className='p-inputtext-sm'
									name='name'
									value={formik.values.name}
									onChange={formik.handleChange}
									placeholder='Masukkan nama'
								/>
								{errorFieldMessage('name')}
							</div>
							<div className='field col-12 md:col-12 mb-2'>
								<label className='block'>Email</label>
								<InputText
									className='p-inputtext-sm'
									name='email'
									value={formik.values.email}
									onChange={formik.handleChange}
									placeholder='Masukkan email'
								/>
								{errorFieldMessage('email')}
							</div>
							<div className='field col-12 md:col-12 mb-2'>
								<label className='block'>Username</label>
								<InputText
									className='p-inputtext-sm'
									name='username'
									value={formik.values.username}
									onChange={formik.handleChange}
									placeholder='Masukkan username'
								/>
								{errorFieldMessage('username')}
							</div>
							<div className='field col-12 md:col-12 mb-2'>
								<label className='block'>Password</label>
								<Password
									name='password'
									value={formik.values.password}
									onChange={formik.handleChange}
									header={header}
									footer={footer}
									toggleMask
								/>
								{errorFieldMessage('password')}
							</div>
							<div className='field col-12 md:col-12 mb-2'>
								<label className='block'>Password Confirm</label>
								<Password
									name='password_retype'
									value={formik.values.password_retype}
									onChange={formik.handleChange}
									feedback={false}
									toggleMask
								/>
								{errorFieldMessage('password_retype')}
							</div>
							<div className='field col-12 md:col-4'>
								<label className='block'>Role</label>
								<Dropdown
									panelClassName='p-dropdown-form'
									name='role'
									options={optionRole}
									optionLabel='nama'
									optionValue='role_id'
									value={formik.values.role}
									onChange={(e) => handleRole(e)}
									showClear={formik.values.role ? true : false}
									scrollHeight='200px'
									placeholder='Select role'
								/>
								{errorFieldMessage('role')}
							</div>
							<div className='field col-12 md:col-4'>
								<label className='block'>Unit Kerja</label>
								<Dropdown
									panelClassName='p-dropdown-form'
									name='unit'
									options={optionUnitKerja}
									optionLabel='nama'
									optionValue='unit_id'
									value={formik.values.unit}
									onChange={formik.handleChange}
									showClear={formik.values.unit ? true : false}
									scrollHeight='200px'
									placeholder='Select unit kerja'
									disabled={showUnitKerja}
								/>
								{errorFieldMessage('unit')}
							</div>
						</div>
					</div>
				</form>
			</Dialog>
		</>
	)
}
