import { FC, Fragment, useState } from 'react'
import Input from '../../../components/Input'
import { useTranslation } from 'react-i18next'
import { isEmail } from '../../../config/func'
import { useUpdateEmail } from '../hooks/useProfileData'
import { ErrorType } from '../../../helpers/types'
import { toast } from '../../../components/Toast'
import Button from '@/components/Button'

type Props = {
    email: string | null,
    isVerified: boolean
}

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

    const { t } = useTranslation('global')
    const [email, setEmail] = useState<string>(props.email ? props.email : '')
    const [isReadOnly, setIsReadOnly] = useState<boolean>(true)
    const updateEmail = useUpdateEmail()

    const handleShowModal = () => {
        updateEmail.mutate({ email: email }, {
            onSuccess: () => {
                toast(t('profile.link_email'), 'success')
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message[0], 'error')
            }
        })
    }

    return (
        <Fragment>
            <div className='flex relative items-end xl:gap-6 gap-3 xl:mt-7 mt-4'>
                <Input
                    label={t('email')}
                    value={email}
                    readOnly={isReadOnly}
                    onChange={(e) => setEmail(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={!isEmail(email)}
                            onClick={handleShowModal}
                            loading={updateEmail.isPending}
                        />
                }
            </div>
        </Fragment>
    )
}

export default Email