import { VisibilityOff, Visibility } from '@mui/icons-material'
import { Stack, InputAdornment, IconButton, Button, Alert } from '@mui/material'
import React, { useState } from 'react'
import { FormTextField } from './HookForm'
import axios from '../config/axios'
import { useForm } from 'react-hook-form'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'

function ResetPassword() {
  const searchParams = new URLSearchParams(document.location.search)
  const { handleSubmit, control } = useForm()
  const navigate = useNavigate()
  const [error, setError] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  async function handleResetPassword(values) {
    const token = searchParams.get('token')
    values.token = token

    if (values.newPassword == values.confirmNewPassword) {
      try {
        await axios
          .post(`https://api.campx.dev/auth-server/auth/reset-password`, values)
          .then((res) => {
            navigate('/login')
            toast.success('Password Changed Successfully')
          })
      } catch (err) {
        if (
          values.newPassword.length == 0 &&
          values.confirmNewPassword.length == 0
        ) {
          setError('Please enter valid password')
        } else if (token == null) {
          setError('Invalid token')
        } else {
          setError(err.response.data.message ?? 'Server Error')
        }
      }
    } else {
      setError("New Password and Confirm New password doesn't match")
    }
  }

  return (
    <>
      <form onSubmit={handleSubmit(handleResetPassword)}>
        <Stack gap={'30px'}>
          <FormTextField
            control={control}
            name="newPassword"
            label="New Password"
            type={showPassword ? 'text' : 'password'}
            required
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    aria-label="toggle password visibility"
                    onClick={() => setShowPassword((prev) => !prev)}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />

          <FormTextField
            control={control}
            name="confirmNewPassword"
            label="Confirm Password"
            type={showConfirmPassword ? 'text' : 'password'}
            required
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    aria-label="toggle password visibility"
                    onClick={() => setShowConfirmPassword((prev) => !prev)}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />

          <Button type="submit">Reset Password</Button>
        </Stack>
      </form>
      {error && (
        <Alert severity="error" sx={{ marginTop: '20px' }}>
          {error}
        </Alert>
      )}
    </>
  )
}

export default ResetPassword
