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

type Props = {
    lastName: string | null | undefined
}

const LastName: FC<Props> = (props: Props) => {

    const { t } = useTranslation('global')
    const [value, setValue] = useState<string>(props.lastName || '')
    const [isReadOnly, setIsReadOnly] = useState<boolean>(true)
    const updateProfile = useUpdateProfile()

    useEffect(() => {
        setValue(props.lastName || '')
    }, [props.lastName])

    const handleSave = () => {
        const params: UpdateProfileType = { lastName: value }
        updateProfile.mutate(params, {
            onSuccess: () => {
                toast(t('success'), 'success')
                setIsReadOnly(true)
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message[0], 'error')
            }
        })
    }

    const isDisabled = value.trim().length === 0 || value === (props.lastName || '')

    return (
        <div className='flex items-end xl:gap-6 gap-3 xl:mt-7 mt-4'>
            <Input
                label={t('profile.last_name')}
                value={value}
                readOnly={isReadOnly}
                onChange={(e) => setValue(e.target.value)}
            />
            {
                isReadOnly ? (
                    <div onClick={() => setIsReadOnly(false)} className='flex cursor-pointer relative -top-3 gap-1 text-[#0047FF] text-xs items-center'>
                        <Edit className='xl:size-[18px] size-4' color='#0047FF' />
                        <div>{t('edit')}</div>
                    </div>
                ) : (
                    <Button
                        label={t('save')}
                        className='px-4 w-fit'
                        disabled={isDisabled}
                        onClick={handleSave}
                        isLoading={updateProfile.isPending}
                    />
                )
            }
        </div>
    )
}

export default LastName


