'use client'

import * as Yup from 'yup'
import { useState } from 'react'
import { useForm } from 'react-hook-form'

import Stack from '@mui/material/Stack'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import InputAdornment from '@mui/material/InputAdornment'
import { Button, TextField, Box } from '@mui/material'
import { yupResolver } from '@hookform/resolvers/yup'
import { useBoolean, useRouter, useSearchParams} from '@/hooks'
import FontAwesome from '@/shared/components/fontawesome'
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons'
import { useSnackbar } from 'notistack'
import { paths } from '@/routes/paths'
import { useCollaboratorStore } from '@/shared/api/stores/CollaboratorStore'
import ConditionalComponent from '@/shared/components/table/ConditionalComponent'



export default function PasswordResetView() {
  const password = useBoolean()
  const confirmPassword = useBoolean()
  const [isSaved, setIsSaved] = useState(false)
  const { enqueueSnackbar } = useSnackbar()
  
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get('email');

  const ResetPasswordSchema = Yup.object().shape({
    newPassword: Yup.string().required('New password is required'),
    confirmPassword: Yup.string()
      .oneOf([Yup.ref('newPassword')], 'Passwords must match')
      .required('Confirmation password is required'),
  })

  const defaultValues = {
    newPassword: '',
    confirmPassword: '',
  }
  const { updateCollaboratorPassword } = useCollaboratorStore()
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: yupResolver(ResetPasswordSchema),
    defaultValues,
  })


  const onSubmit = async (data: any) => {
    if (!email) {
      enqueueSnackbar('Email parameter is missing', { variant: 'error' })
      return
    }
    
    try {
        await updateCollaboratorPassword({
            email: email,
            password: data.newPassword,
          })
      setIsSaved(true)
    } catch (error: any) {
      reset()
      enqueueSnackbar(error?.message || 'Password reset failed', { variant: 'error' })
    }
  }

  const handleContinue = () => {
    router.push(paths.auth.jwt.login) 
  }

  return (
    <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '57vh' }}>
      <Stack spacing={3} sx={{ width: '100%', maxWidth: 450, padding: 3 }}>
        <Typography variant="h5" sx={{ textAlign: 'center' }}>Réinitialiser votre mot de passe</Typography>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Stack spacing={2.5}>
            <TextField
              {...register('newPassword')}
              label="Nouveau mot de passe"
              type={password.value ? 'text' : 'password'}
              fullWidth
              error={!!errors.newPassword}
              helperText={errors.newPassword?.message}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={password.onToggle} edge="end">
                      <FontAwesome icon={password.value ? faEye : faEyeSlash} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <TextField
              {...register('confirmPassword')}
              label="Confirmer le mot de passe"
              type={confirmPassword.value ? 'text' : 'password'}
              fullWidth
              error={!!errors.confirmPassword}
              helperText={errors.confirmPassword?.message}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={confirmPassword.onToggle} edge="end">
                      <FontAwesome icon={confirmPassword.value ? faEye : faEyeSlash} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <Button
              fullWidth
              color="primary"
              size="large"
              type="submit"
              variant="contained"
              disabled={isSubmitting}
            >
              Save
            </Button>
          </Stack>
        </form>

        <ConditionalComponent isValid={isSaved}>
          <Stack spacing={2} sx={{ mt: 3 }}>
            <Button
              fullWidth
              color="primary"
              size="large"
              variant="outlined"
              onClick={handleContinue}
              disabled={!isSaved}
            >
              Continue
            </Button>
          </Stack>
        </ConditionalComponent>
      </Stack>

      <Box
        sx={{
          display: { xs: 'none', sm: 'block' },
          position: 'absolute',
          top: 0,
          left: 0,
          width: '50%',
          height: '100%',
          background: 'url(/path/to/illustration.png) no-repeat center center',
          backgroundSize: 'contain',
        }}
      />
    </Box>
  )
}
