import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import Input from '../../components/Input'
import RolePermissionsSelector from './components/RolePermissionsSelector'
import { useGetPermissions, useGetRoleDetail, useUpdateRole } from './hooks/useUserData'
import PageLoading from '../../components/PageLoading'
import { useFormik } from 'formik'
import { CreateRoleType, RolePermissionType } from './types/UserTypes'
import * as Yup from 'yup'
import { useNavigate, useParams } from 'react-router-dom'
import { Pages } from '../../config/Pages'
import { ErrorType } from '../../helpers/types'
import { toast } from '../../components/Toast';

const RoleUpdate: FC = () => {

    const { id } = useParams()
    const { t } = useTranslation('global')
    const navigate = useNavigate()
    const [permissions, setPermissions] = useState<string[]>([])
    const getPermissions = useGetPermissions()
    const { data: roleDetail, isPending: isRoleDetailPending } = useGetRoleDetail(id || '')
    const updateRole = useUpdateRole()

    const handleAdd = (permissionId: string) => {
        if (permissions.includes(permissionId)) {
            setPermissions(permissions.filter(permission => permission !== permissionId))
        } else {
            setPermissions([...permissions, permissionId])
        }
    }

    const formik = useFormik<CreateRoleType>({
        initialValues: {
            name: '',
            permissions: [],
        },
        validationSchema: Yup.object({
            name: Yup.string()
                .required(t('errors.required'))
        }),
        onSubmit: (values) => {
            if (permissions.length > 0) {
                values.permissions = permissions
                updateRole.mutate({ id: id || '', params: values }, {
                    onSuccess: () => {
                        toast(t('success'), 'success')
                        navigate(Pages.users.roleList)
                    },
                    onError: (error: ErrorType) => {
                        toast(error.response?.data?.error?.message[0], 'error')
                    }
                })
            } else {
                toast(t('user.error_count_permission'), 'error')
            }
        }
    })

    useEffect(() => {
        const role = roleDetail?.data?.role
        if (role) {
            formik.setFieldValue('name', role.name)
            const permissionIds = role.permissions?.map((permission: string | RolePermissionType) =>
                typeof permission === 'string' ? permission : permission.id
            ) || []
            setPermissions(permissionIds)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [roleDetail])

    if (getPermissions.isPending || isRoleDetailPending) {
        return <PageLoading />
    }

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('user.update_role')}
                </div>
                <Button
                    className='w-fit px-8'
                    onClick={() => formik.handleSubmit()}
                    isLoading={updateRole.isPending}
                >
                    <div className='flex gap-2'>
                        <TickCircle
                            className='size-5'
                            color='white'
                        />
                        <div className='text-sm'>
                            {t('user.submit_role')}
                        </div>
                    </div>
                </Button>
            </div>

            <div className='flex gap-6 mt-9'>
                <div className='flex-1  bg-white py-10 xl:px-10 px-5 rounded-3xl'>

                    <Input
                        label={t('user.title_role')}
                        {...formik.getFieldProps('name')}
                        error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                    />

                    <div className='mt-8'>
                        <div className='text-sm'>
                            {t('user.permissions')}
                        </div>

                        <RolePermissionsSelector
                            permissions={getPermissions.data?.data?.permissions ?? []}
                            selectedIds={permissions}
                            onToggle={handleAdd}
                        />
                    </div>

                </div>
            </div>
        </div>
    )
}

export default RoleUpdate
