import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../components/Button'
import { useCreateGroup, useGetUsers } from './hooks/useUserData'
import { useFormik } from 'formik'
import { TickCircle } from 'iconsax-react'
import { CreateGroupType, UserItemType } from './types/UserTypes'
import * as Yup from 'yup'
import PageLoading from '../../components/PageLoading'
import Input from '../../components/Input'
import CheckBoxComponent from '../../components/CheckBoxComponent'
import Textarea from '../../components/Textarea'
import { useNavigate } from 'react-router-dom'
import { Pages } from '../../config/Pages'
import { toast } from 'react-toastify'
import { ErrorType } from '../../helpers/types'

const GroupCreate: FC = () => {

    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const [users, setUsers] = useState<string[]>([])
    const createGroup = useCreateGroup()
    const getUsers = useGetUsers('')

    const formik = useFormik<CreateGroupType>({
        initialValues: {
            name: '',
            description: '',
            userIds: []
        },
        validationSchema: Yup.object({
            name: Yup.string()
                .required(t('errors.required')),
        }),
        onSubmit: (values) => {
            if (users.length > 0) {
                values.userIds = users
                createGroup.mutate(values, {
                    onSuccess: () => {
                        formik.resetForm()
                        navigate(Pages.users.groupList)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            } else {
                toast.error(t('user.error_count_users'))
            }
        }
    })

    const handleAdd = (id: string) => {
        if (users.includes(id)) {
            setUsers(users.filter(user => user !== id))
        } else {
            setUsers([...users, id])
        }
    }

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

            {
                getUsers.isPending ?
                    <PageLoading />
                    :
                    <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.name')}
                                {...formik.getFieldProps('name')}
                                error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                            />

                            <div className='mt-8'>
                                <Textarea
                                    label={t('description')}
                                    {...formik.getFieldProps('description')}
                                    error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
                                />
                            </div>

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

                                <div className='mt-5 text-sm flex flex-wrap gap-5'>
                                    {
                                        getUsers.data?.data?.users?.map((item: UserItemType) => {
                                            return (
                                                <div key={item.id} className='flex flex-1 min-w-[23%] items-center'>
                                                    <CheckBoxComponent
                                                        checked={users.includes(item.id)}
                                                        onChange={() => handleAdd(item.id)}
                                                    />
                                                    <div className='mt-0.5'>{item.firstName + ' ' + item.lastName}</div>
                                                </div>
                                            )
                                        })
                                    }
                                </div>
                            </div>

                        </div>
                    </div>
            }

        </div>
    )
}

export default GroupCreate