'use client'
import { Dialog, DialogActions, DialogContent, IconButton, InputAdornment, Typography, useTheme } from '@mui/material'
import { Grid2 } from '@mui/material'
import Button from '@/@core/components/mui/Button'
import { useTranslations } from 'next-intl'
import CustomTextField from '@/@core/components/mui/TextField'
import { useForm, Controller, SubmitHandler } from 'react-hook-form'
import { useAtom, useAtomValue } from 'jotai'
import { codeModalAtom, emailVerificationModalAtom } from '@/components/store/state-store-email-status'
import { useState } from 'react'
import { useSendPassword } from '@/@core/hooks/reset_password'
import { zodResolver } from '@hookform/resolvers/zod'
import { PasswordReset, PasswordResetSchema } from '@/utils/validators/reset-password'
import { useAuth } from '@/hooks'
import Swal from 'sweetalert2'

type FormData = {
  password: any
  confirm_password: any
  code: any
}

const DialogNewPassword = () => {
  const t = useTranslations('RESET-PASSWORD')
  const tM = useTranslations('')
  const [emailModal, setEmailModal] = useAtom(emailVerificationModalAtom)
  const [isPasswordShown, setIsPasswordShown] = useState(false)
  const [isConfirmPasswordShown, setIsConfirmPasswordShown] = useState(false)

  const data_Email_code = useAtomValue(emailVerificationModalAtom)
  const [otp, setOtp] = useState('')
  const theme = useTheme()

  const handleClickShowPassword = () => setIsPasswordShown(show => !show)
  const handleClickShowConfirmPassword = () => setIsConfirmPasswordShown(show => !show)

  const {
    control,
    handleSubmit,
    register,
    formState: { errors }
  } = useForm<any>({
    resolver: zodResolver(PasswordResetSchema),
    defaultValues: { password: '', confirm_password: '' }
  })

  const { mutate, isPending, isError } = useSendPassword()

  const { logout, user } = useAuth()

  const handleClose = () => {
    setEmailModal({ open: false, email: null })
  }
  const onSubmit: SubmitHandler<PasswordReset> = async values => {
    mutate(
      {
        identifier: emailModal.email,
        code: data_Email_code?.code,
        password: values.password,
        confirm_password: values.confirm_password
      },
      {
        onSuccess() {
          handleClose()
          setEmailModal({
            open: false,
            email: emailModal.email
          })
          Swal.fire({
            text: tM('MESSAGES.CHANGE_PASSWORD_SUCCESSFULLY'),
            timer: 4000,
            icon: 'success',
            background: theme.palette.background.default, // Set background to theme background
            color: theme.palette.text.primary,
            showClass: {
              popup: 'animate__animated animate__fadeInUp animate__faster'
            },
            hideClass: {
              popup: 'animate__animated animate__fadeOutDown animate__faster'
            }
          }).then(async () => {
            if (user) {
              await logout.mutate()
            }
          })
        },
        onError() {}
      }
    )
  }

  return (
    <Dialog open={emailModal.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>
          <Controller
            name='password'
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <CustomTextField
                {...field}
                label={t('password')}
                fullWidth
                type={isPasswordShown ? 'text' : 'password'}
                placeholder='********'
                slotProps={{
                  input: {
                    endAdornment: (
                      <InputAdornment position='end'>
                        <IconButton edge='end' onClick={handleClickShowPassword} onMouseDown={e => e.preventDefault()}>
                          <i className={isPasswordShown ? 'tabler-eye' : 'tabler-eye-off'} />
                        </IconButton>
                      </InputAdornment>
                    ),
                    dir: 'ltr'
                  }
                }}
                {...(errors.password && { error: true, helperText: errors.password.message as any })}
              />
            )}
          />
          <Controller
            name='confirm_password'
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <CustomTextField
                {...field}
                label={t('confirm_password')}
                fullWidth
                type={isConfirmPasswordShown ? 'text' : 'password'}
                placeholder='********'
                slotProps={{
                  input: {
                    endAdornment: (
                      <InputAdornment position='end'>
                        <IconButton
                          edge='end'
                          onClick={handleClickShowConfirmPassword}
                          onMouseDown={e => e.preventDefault()}
                        >
                          <i className={isConfirmPasswordShown ? 'tabler-eye' : 'tabler-eye-off'} />
                        </IconButton>
                      </InputAdornment>
                    ),
                    dir: 'ltr'
                  }
                }}
                {...(errors.confirm_password && { error: true, helperText: errors.confirm_password.message as any })}
              />
            )}
          />
        </Grid2>
      </DialogContent>
      <DialogActions sx={{ justifyContent: 'end', gap: 'px' }}>
        <Button color='error' variant='outlined' onClick={handleClose}>
          {t('cancel')}
        </Button>
        <Button color='primary' variant='contained' onClick={handleSubmit(onSubmit)} isLoading={isPending}>
          {t('submit')}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default DialogNewPassword
