import { zodResolver } from '@hookform/resolvers/zod'; import Image from 'next/image'; import { useTranslations } from 'next-intl'; import { useState } from 'react'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import { Button } from '@/components/ui/common/Button'; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/common/Dialog'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, } from '@/components/ui/common/Form'; import { InputOTP, InputOTPGroup, InputOTPSlot, } from '@/components/ui/common/InputOTP'; import { useEnableTotpMutation, useGenerateTotpSecretQuery, } from '@/graphql/generated/output'; import { useCurrent } from '@/hooks/useCurrent'; import { type TypeEnableTotpSchema, enableTotpSchema, } from '@/schemas/user/enable-totp.schema'; export const EnableTotp = () => { const t = useTranslations('dashboard.settings.account.twoFactor.enable'); const [isOpen, setIsOpen] = useState(false); const { refetch } = useCurrent(); const { data, loading: isLoadingGenerate } = useGenerateTotpSecretQuery(); const twoFactorAuth = data?.generateTotpSecret; const form = useForm({ resolver: zodResolver(enableTotpSchema), defaultValues: { pin: '', }, }); const [enable, { loading: isLoadingEnable }] = useEnableTotpMutation({ onCompleted() { void refetch(); setIsOpen(false); toast.success(t('successMessage')); }, onError() { toast.error(t('errorMessage')); }, }); const { isValid } = form.formState; function onSubmit(values: TypeEnableTotpSchema) { void enable({ variables: { data: { secret: twoFactorAuth?.secret ?? '', pin: values.pin, }, }, }); } return ( {t('heading')}
{twoFactorAuth?.qrcodeUrl ? t('qrInstructions') : ''} QR
{twoFactorAuth?.secret ? t('secretCodeLabel') + twoFactorAuth.secret : ''}
( {t('pinLabel')} {t('pinDescription')} )} />
); };