'use client'

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

import Link from '@mui/material/Link'
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 } from '@mui/material'
import { yupResolver } from '@hookform/resolvers/yup'
import { useBoolean, useRouter } from '@/hooks'
import FontAwesome from '@/shared/components/fontawesome'
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons'
import { useSnackbar } from 'notistack'
import { useAuthStore } from '@/shared/api/stores/authStore'


export default function JwtLoginView() {
  const { login } = useAuthStore()
  const password = useBoolean()
  const { enqueueSnackbar } = useSnackbar()

  const LoginSchema = Yup.object().shape({
    email: Yup.string().required('Email is required').email('Email must be a valid email address'),
    password: Yup.string().required('Password is required'),
  })

  const defaultValues = {
    email: '',
    password: '',
  }

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: yupResolver(LoginSchema),
    defaultValues,
  })

 const router = useRouter()

const onSubmit = async (data: any) => {
  try {
    await login({ username: data.email, password: data.password })
    router.push('/dashboard') 
  } catch (error: any) {
    reset()
    enqueueSnackbar(error?.message || 'Login failed', { variant: 'error' })
  }
}

  return (
    <>
      <Stack spacing={2} sx={{ mb: 5 }}>
        <Typography variant="h4">Login</Typography>
        <Stack direction="row" spacing={0.5}>
          <Typography variant="body2">New user?</Typography>
          <Link href="#" variant="subtitle2">
            Create an account
          </Link>
        </Stack>
      </Stack>

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack spacing={2.5}>
          <TextField
            {...register('email')}
            label="Email address"
            fullWidth
            error={!!errors.email}
            helperText={errors.email?.message}
          />
          <TextField
            {...register('password')}
            label="Password"
            type={password.value ? 'text' : 'password'}
            fullWidth
            error={!!errors.password}
            helperText={errors.password?.message}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={password.onToggle} edge="end">
                    <FontAwesome icon={password.value ? faEye : faEyeSlash} />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
          <Link href="#" variant="body2" color="inherit" underline="always" sx={{ alignSelf: 'flex-end' }}>
            Forgot password?
          </Link>
          <Button
            fullWidth
            color="primary"
            size="large"
            type="submit"
            variant="contained"
            disabled={isSubmitting}
          >
            Login
          </Button>
        </Stack>
      </form>
    </>
  )
}
