import Button from '@/components/Button'
import Input from '@/components/Input'
import { toast } from '@/components/Toast'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useCreateDomain, useGetDomains } from '../hooks/useDomainData'
import { ErrorType } from '@/helpers/types'

const CreateDomain: FC = () => {

    const { t } = useTranslation()
    const { mutate: createDomain, isPending } = useCreateDomain()
    const { data: domains } = useGetDomains()
    const [domain, setDomain] = useState('')
    const [isVerified, setIsVerified] = useState<boolean>(false)

    useEffect(() => {
        if (domains?.data?.domain) {
            setDomain(domains?.data?.domain?.name)
            if (domains?.data?.domain?.isVerified) {
                setIsVerified(true)
            }
        }
    }, [domains])


    const handleCreateDomain = () => {
        createDomain({
            name: domain,
            notes: domain
        }, {
            onSuccess: (data) => {
                toast(data.message, 'success')
                setDomain('')
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message[0], 'error')
            }
        })
    }
    return (
        <div className='flex xl:flex-row gap-4 flex-col justify-between mt-9 items-end'>
            <div>
                <div className='xl:text-lg'>
                    {t('setting.record_dns')}
                </div>
                <p className='mt-2 xl:text-sm text-xs font-extralight'>
                    {t('setting.record_dns_description')}
                </p>
            </div>

            <div className='flex gap-2'>
                <Input
                    placeholder={t('setting.your_domain')}
                    className='xl:w-[300px]'
                    value={domain}
                    onChange={(e) => setDomain(e.target.value)}
                    readOnly={isVerified}
                />

                {
                    !isVerified &&
                    <Button
                        variant='secondary'
                        className='w-fit xl:px-14 px-8 border border-black'
                        label={t('setting.submit')}
                        onClick={handleCreateDomain}
                        loading={isPending}
                    />
                }
            </div>
        </div>
    )
}

export default CreateDomain