import { type FC, useEffect } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { TickCircle } from 'iconsax-react'
import { toast } from 'react-toastify'
import { useNavigate, useParams } from 'react-router-dom'
import Button from '@/components/Button'
import Input from '@/components/Input'
import { Checkbox } from '@/components/ui/checkbox'
import { useUpdateRole, useGetRoleDetails, useGetPermissions } from './hooks/useRolesData'
import type { CreateRoleType } from './types/Types'
import { Pages } from '@/config/Pages'
import type { ErrorType } from '@/helpers/types'
import { extractErrorMessage } from '@/config/func'
import PageLoading from '@/components/PageLoading'

const UpdateRole: FC = () => {
    const { id } = useParams<{ id: string }>()
    const { data: roleData, isLoading } = useGetRoleDetails(id || '')
    const { data: permissionsData } = useGetPermissions()
    const { mutate: updateRole, isPending } = useUpdateRole()
    const navigate = useNavigate()

    const role = roleData?.data

    const formik = useFormik<CreateRoleType>({
        initialValues: {
            name: '',
            permissionIds: [],
        },
        validationSchema: Yup.object().shape({
            name: Yup.string().required('نام نقش الزامی است'),
            permissionIds: Yup.array().of(Yup.string()),
        }),
        onSubmit: (values) => {
            if (!id) return
            updateRole(
                { id, params: values },
                {
                    onSuccess: () => {
                        toast.success('نقش با موفقیت به‌روزرسانی شد')
                        navigate(Pages.roles.list)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(extractErrorMessage(error))
                    },
                }
            )
        },
    })

    useEffect(() => {
        if (role) {
            formik.setValues({
                name: role.name || '',
                permissionIds: role.permissions?.map((p) => p.id) || [],
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [role])

    if (isLoading) {
        return <PageLoading />
    }

    if (!role) {
        return (
            <div className='w-full mt-4 flex justify-center items-center'>
                <div>نقش یافت نشد</div>
            </div>
        )
    }

    return (
        <div className='mt-5'>
            <div className='flex w-full justify-between items-center'>
                <div className='text-lg font-light'>
                    ویرایش نقش
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isloading={isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle className='size-5' color='white' />
                            <div>ثبت تغییرات</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='mt-6'>
                <div className='bg-white rounded-3xl p-6'>
                    <div className='mb-4'>
                        <Input
                            label='نام نقش'
                            name='name'
                            value={formik.values.name}
                            onChange={formik.handleChange}
                            error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                        />
                    </div>
                    <div className='mt-6'>
                        <div className='text-sm mb-3'>دسترسی‌ها</div>
                        {permissionsData?.data && permissionsData.data.length > 0 ? (
                            <div className='flex gap-6 flex-wrap'>
                                {permissionsData.data.map((permission) => (
                                    <div key={permission.id} className='flex items-center gap-2'>
                                        <Checkbox
                                            checked={formik.values.permissionIds.includes(permission.id)}
                                            onCheckedChange={(checked) => {
                                                const currentIds = formik.values.permissionIds
                                                if (checked) {
                                                    formik.setFieldValue('permissionIds', [...currentIds, permission.id])
                                                } else {
                                                    formik.setFieldValue('permissionIds', currentIds.filter((id) => id !== permission.id))
                                                }
                                            }}
                                        />
                                        <label className='text-xs cursor-pointer'>{permission.title}</label>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className='text-sm text-gray-500'>دسترسی‌ای یافت نشد</div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default UpdateRole