'use client'

import { InputMui } from '@/components/mui/inputs'
import { Button } from '@/components/ui/button'
import { AuthContext } from '@/contexts/auth-context'
import { AxiosError } from 'axios'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useContext } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import globo from '../../../public/images/globo.svg'

type FormLogin = {
  email: string
  password: string
}

export default function Login() {
  const { handleSubmit, register } = useForm<FormLogin>()
  const { signIn } = useContext(AuthContext)
  const router = useRouter()

  const onSubmit = async (data: FormLogin) => {
    try {
      await signIn(data)
      router.push('/admin')
    } catch (error) {
      if (error instanceof AxiosError) {
        const { message } = error.response?.data
        toast.error(`${message}`)
      }
    }
  }

  return (
    <main>
      <section className=" container flex flex-col justify-center items-center space-y-10 h-[723px]">
        <Image
          src={globo}
          width={77}
          height={77}
          alt="Imagem demonstrativa de um globo"
        />
        <h1 className="text-green-400 text-2xl">Área administrativa</h1>
        <h2 className="text-gray-50">
          Acesso exclusivo para usuários cadastrados.
        </h2>
        <form
          onSubmit={handleSubmit(onSubmit)}
          className="w-full md:w-[600px] flex flex-col gap-8 order-4"
        >
          <div className="flex flex-col space-y-6">
            <div className="flex flex-col space-y-4">
              <InputMui
                label="E-mail"
                variant="outlined"
                type="email"
                name="email"
                register={register}
              />
              <InputMui
                label="Senha"
                variant="outlined"
                type="password"
                name="password"
                register={register}
              />
            </div>
            {/* <div className="flex items-center space-x-2">
              <Checkbox id="remember" />
              <label
                htmlFor="remember"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                Lembrar-me
              </label>
            </div> */}
            <Button className="rounded-sm" type="submit">
              {/* <Link href="/admin">Entrar</Link> */}
              Entrar
            </Button>
            <Button
              variant={'link'}
              asChild
              className="text-green-400 uppercase"
            >
              <Link href="#">Recuperar senha</Link>
            </Button>
          </div>
        </form>
      </section>
    </main>
  )
}
