import { FC, useEffect, useState } from 'react'
import Input from '../../../components/Input'
import { Edit } from 'iconsax-react'
import { useTranslation } from 'react-i18next'
import Button from '../../../components/Button'
import { useCheckUserName, useUpdateProfile } from '../hooks/useProfileData'
import { CheckUserNameType, UpdateProfileType } from '../types/ProfileTypes'
import { toast } from '../../../components/Toast'
import { ErrorType } from '../../../helpers/types'

type Props = {
    username: string | null,
}
const Username: FC<Props> = (props: Props) => {

    const { t } = useTranslation('global')
    const [username, setUsername] = useState<string>(props.username ? props.username : '')
    const [canSave, setCanSave] = useState<boolean>(false)
    const [canEdit, setCanEdit] = useState<boolean>(false)
    const [status, setStatus] = useState<'success' | 'error' | ''>('')
    const checkUsername = useCheckUserName()
    const updateProfile = useUpdateProfile()

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value
        setCanSave(false)
        if (value.indexOf(' ') === -1) {
            if (value.length <= 3) {
                setUsername(value)
                return
            }
            setStatus('')
            const params: CheckUserNameType = {
                value: e.target.value,
                type: 'userName'
            }
            setUsername(e.target.value)
            checkUsername.mutate(params, {
                onSuccess() {
                    setStatus('success')
                    setCanSave(true)
                },
                onError() {
                    setStatus('error')
                }
            })
        }
    }

    const handleSave = () => {
        const params: UpdateProfileType = {
            userName: username
        }

        updateProfile.mutate(params, {
            onSuccess: () => {
                toast(t('profile.username_save_success'), 'success')
                setCanEdit(false)
                setCanSave(false)
                setStatus('')
            },
            onError(error: ErrorType) {
                toast(error.response?.data?.error?.message[0], 'error')
            },
        })
    }

    useEffect(() => {
        if (username !== props.username) {
            setUsername(props.username ? props.username : '')
        }
    }, [props.username])


    return (
        <>
            <div className='flex items-end xl:gap-6 gap-3'>
                <div className='relative w-full'>
                    <Input
                        label={t('profile.username')}
                        value={username}
                        readOnly={!canEdit}
                        onChange={handleChange}
                        minLength={3}
                        maxLength={20}
                    />

                    {
                        checkUsername.isPending &&
                        <div className='absolute left-4 top-8'>
                            <div className='loader'></div>
                        </div>
                    }
                </div>
                <div className='flex relative  gap-1 text-[#0047FF] text-xs items-center'>
                    {
                        !canEdit ?
                            <div onClick={() => setCanEdit(true)} className='flex gap-1 cursor-pointer relative -top-3'>
                                <Edit className='xl:size-[18px] size-4' color='#0047FF' />
                                <div>
                                    {t('edit')}
                                </div>
                            </div>
                            :
                            <Button
                                label={t('save')}
                                onClick={handleSave}
                                className='px-4'
                                disabled={!canSave}
                                isLoading={updateProfile.isPending}
                            />
                    }

                </div>
            </div>
            {
                status === 'success' ?
                    <div className='text-xs text-green-500 mt-2'>
                        {t('profile.username_available')}
                    </div>
                    :
                    status === 'error' ?
                        <div className='text-xs text-red-500 mt-2'>
                            {t('profile.username_not_available')}
                        </div>
                        : null
            }
        </>
    )
}

export default Username