import UserStore from '@/store/UserStore'
import { yupResolver } from '@hookform/resolvers/yup'
import { useTranslation } from 'next-i18next'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { FormProvider, SubmitHandler, useForm } from 'react-hook-form'
import * as yup from 'yup'
import Logonegro from '../../../public/images/logo_sobre_negro.png'
import { InputRegister } from '../../../types'
import CheckBox from '../atoms/CheckBox'
import Input from '../atoms/Input'

export default function FormRegister() {
  const { t } = useTranslation()
  const { setUser } = UserStore()

  const Schema = yup.object({
    firstName: yup.string().required(t('common:userNameMandatory')),
    lastName: yup.string().required('El apellido es obligatorio'),
    email: yup.string().email(t('common:emailNoCorrecto')).required(t('common:enterYourEmail')),
    password: yup.string().min(9, 'a dooonde vas flipado minimo 9').required(t('common:passwordMandatory')),
    phone: yup.string().required('El telefono es obligatorio'),
    birthday: yup.string().required('La fecha de cumpleaños es obligatoria'),
    // profilePicture: yup.string(),
    privacyPolicy: yup.boolean().oneOf([true], 'Debes aceptar los términos para poder continuar')
  })
  const methods = useForm<InputRegister>({
    resolver: yupResolver(Schema),
    defaultValues: {
      firstName: '',
      lastName: '',
      email: '',
      birthday: '',
      password: '',
      phone: '',
      privacyPolicy: false
    }
  })
  const {
    handleSubmit,
    formState: { errors }
  } = methods
  const router = useRouter()
  const onSubmit: SubmitHandler<InputRegister> = async (data) => {
    console.log(data)
    const url = `${process.env.BASE_URL}api/register`

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      })
      if (response.ok) {
        const responseData = await response.json()
        setUser(responseData)
        router.push('/home')
        console.log(responseData, 'responseData')
      } else {
        console.error('Error al realizar la solicitud')
      }
    } catch (error) {
      console.error('Error al realizar la solicitud', error)
    }
  }

  return (
    <div className="flex flex-col items-center p-8">
      <div className="flex justify-center h-[140px] w-[200px]">
        <Image src={Logonegro} alt="Logo League Ranks" />
      </div>
      <main className={`h-full  lg:px-80 lg:pb-24 px-5 py-7`}>
        <FormProvider {...methods}>
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="flex flex-col gap-4 bg-white shadow-md rounded px-8 pt-6 pb-8 "
          >
            <div>
              <h5>{t('common:register')}</h5>
              <span className="md:text-xs text-[10px]">Crea una nueva cuenta</span>
            </div>
            <div className="flex md:flex-row flex-col md:gap-3 gap-4">
              <Input name="firstName" label={t('common:nombre')} type="text" placeholder={t('common:tuNombre')} />
              <Input name="lastName" label={t('common:lastName')} type="text" placeholder={t('common:lastName')} />
            </div>
            <Input name="phone" label={t('common:phone')} type="text" placeholder={t('common:phone')} />
            <Input name="birthday" label={t('common:birthday')} type="date" placeholder={t('common:birthday')} />
            <Input name="email" type="text" label={t('common:email')} placeholder={t('common:email')} />
            <Input name="password" type="password" label={t('common:password')} placeholder={t('common:password')} />
            <CheckBox
              name="privacyPolicy"
              label={t('common:privacyPolicy')}
              classNameContent="md:flex-row flex-col md:gap-2 gap-3"
              classNameLabel={'order-first md:order-last'}
              classNameInput={'md:order-first order-last'}
            />
            <div className="flex flex-col items-center justify-between ">
              <button
                className="w-full bg-primary-500 hover:bg-primary-800 text-black font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline my-4"
                type="submit"
              >
                {t('common:register')}
              </button>
            </div>
          </form>
        </FormProvider>
      </main>
    </div>
  )
}
