'use client'

import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { zodResolver } from '@hookform/resolvers/zod'
import Image from 'next/image'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import signUpImage from '../../public/images/sign-up.png'
import { InputMui } from './mui/inputs'

type FormSignUpTypes = {
  fullname: string
  email: string
  whatsapp: string
  area: string
  course: string
}
const schema = z
  .object({
    fullname: z.string().min(5, { message: 'Digite seu nome completo' }),
    email: z.string().email({ message: 'E-mail inválido' }),
    whatsapp: z
      .string()
      .min(10, { message: 'Digite seu whatsapp com o DDD' })
      .max(13, { message: 'Digite apenas o número do seu whatsapp' }),
    area: z.string().min(2, { message: 'Informe a área' }),
    course: z.string().min(2, { message: 'Informe o curso' }),
  })
  .required()

export function SignUp() {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<FormSignUpTypes>({
    resolver: zodResolver(schema),
  })
  const [status, setStatus] = useState('')

  async function onSubmit(data: FormSignUpTypes) {
    setStatus('Enviando...')
    try {
      const response = await fetch('/api/send-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (response.ok) {
        toast.success('E-mail enviado com sucesso!')
        setStatus('Inscrever')
        reset()
      } else {
        toast.error('Falha ao enviar E-mail!')
        setStatus('Inscrever')
      }
    } catch (error) {
      setStatus('Inscrever')
    }
  }

  return (
    <section className="w-full bg-gradient-to-r from-green-700 to-green-50 pb-6 md:py-6 md:pb-0">
      <div className="container overflow-hidden relative h-auto flex flex-col md:flex-row gap-2 justify-between items-center ">
        <p className="max-w-[268px] my-6 md:max-w-[420px] text-xl text-gray-50 md:text-2xl lg:text-3xl text-center order-3 md:order-1">
          Inscreva-se e receba novidades sobre cursos ou areas de interesse
        </p>
        <Image
          src={signUpImage}
          height={450}
          width={331}
          alt="Imagem demonstrativa de uma pessoa se cadastrando na plataforma"
          className="mt-auto md:min-h-[550px] object-cover order-1 md:order-2"
        />
        <Separator className="h-2 w-screen order-2 md:hidden -mt-3 bg-yellow-100" />
        <form
          onSubmit={handleSubmit(onSubmit)}
          className="w-full md:w-[600px] flex flex-col gap-8 order-4"
        >
          <InputMui
            type="text"
            variant="standard"
            label="Nome completo"
            name="fullname"
            register={register}
          />
          {errors.fullname?.message && (
            <p className="text-red-600">{errors.fullname?.message}</p>
          )}
          <InputMui
            type="number"
            variant="standard"
            label="Whatsapp"
            name="whatsapp"
            register={register}
          />
          {errors.whatsapp?.message && (
            <p className="text-red-600">{errors.whatsapp?.message}</p>
          )}
          <InputMui
            type="text"
            variant="standard"
            label="Área de interesse"
            name="area"
            register={register}
          />
          {errors.area?.message && (
            <p className="text-red-600">{errors.area?.message}</p>
          )}
          <InputMui
            type="text"
            variant="standard"
            label="E-mail"
            name="email"
            register={register}
          />
          {errors.email?.message && (
            <p className="text-red-600">{errors.email?.message}</p>
          )}
          <InputMui
            type="text"
            variant="standard"
            label="Curso desejado"
            name="course"
            register={register}
          />
          {errors.course?.message && (
            <p className="text-red-600">{errors.course?.message}</p>
          )}
          <Button
            type="submit"
            variant="secondary"
            className="uppercase max-w-32 mx-auto md:mb-6"
          >
            {status || 'Inscrever'}
          </Button>
        </form>
      </div>
    </section>
  )
}
