'use client'
import { Dialog, DialogActions, DialogContent, Typography } from '@mui/material'
import { Grid2 } from '@mui/material'
import Button from '@/@core/components/mui/Button'

import { useTranslations } from 'next-intl'
import { SubmitHandler, useForm } from 'react-hook-form'
import CustomTextField from '@/@core/components/mui/TextField'
import { useSetAtom } from 'jotai'
import { codeModalAtom } from '@/components/store/state-store-email-status'
import { zodResolver } from '@hookform/resolvers/zod'
import { EmailResetPassword, EmailResetPasswordAddSchema } from '@/utils/validators/reset-password'
import { useSendEmail } from '@/@core/hooks/reset_password'

type TDialogResetPassword = {
  open: boolean
  handleClose: () => any
}

const DialogResetPasswordOutside = ({ open, handleClose }: TDialogResetPassword) => {
  const t = useTranslations('RESET-PASSWORD')
  const setEmailModal = useSetAtom(codeModalAtom)

  const { mutate, isPending, isError } = useSendEmail()

  const {
    handleSubmit,
    register,
    reset,
    formState: { errors }
  } = useForm<any>({
    resolver: zodResolver(EmailResetPasswordAddSchema),
    defaultValues: {}
  })

  const onSubmit: SubmitHandler<EmailResetPassword> = async values => {
    mutate(values, {
      onSuccess(data) {
        handleClose()
        setEmailModal({ open: true, email: values.email, code: data?.data })
        reset({ email: '' })
      },
      onError() {
        reset({ email: '' })
      }
    })
  }
  return (
    <Dialog open={open} onClose={handleClose} maxWidth='xs' fullWidth>
      <DialogContent>
        <Grid2 sx={{ display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'center' }}>
          <Typography sx={{ fontWeight: 'bold', fontSize: '20px', textAlign: 'center' }}>
            {t('change_password')}
          </Typography>
          <Typography sx={{ textAlign: 'center' }}>{t('otp_messages')}</Typography>
          <CustomTextField
            {...register('email')}
            type='email'
            label={t('email')}
            placeholder='example@mail.com'
            fullWidth
            {...(errors.email && { error: true, helperText: errors.email.message as any })}
          />
        </Grid2>
      </DialogContent>
      <DialogActions sx={{ justifyContent: 'end', gap: 2 }}>
        <Button color='error' variant='outlined' onClick={handleClose}>
          {t('cancel')}
        </Button>
        <Button
          color='primary'
          variant='contained'
          isLoading={isPending}
          disabled={isPending}
          onClick={handleSubmit(onSubmit)}
        >
          {t('submit')}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default DialogResetPasswordOutside
