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 { useForm } from 'react-hook-form'
import { SubmitHandler } from 'react-hook-form/dist/types'
import * as yup from 'yup'
import Logonegro from '../../../public/images/logo_sobre_negro.png'
import { InputsLogin, User } from '../../../types'
import { ErrorSpan } from '../atoms/ErrorSpan'

export default function FormLogin() {
  const { t } = useTranslation()
  const { setUser } = UserStore()
  const userSchema = yup.object({
    username: yup.string().email(t('common:emailNoCorrecto')).required(t('common:userNameMandatory')),
    password: yup.string().required(t('common:passwordMandatory'))
  })

  const {
    register,
    watch,
    handleSubmit,
    formState: { errors }
  } = useForm<InputsLogin>({
    resolver: yupResolver(userSchema)
  })
  const router = useRouter()

  const onSubmit: SubmitHandler<InputsLogin> = async (data) => {
    console.log(data)
    const url = `${process.env.BASE_URL}api/login_check`
    const username = 'developer'
    const password = 'mambita'
    // const base64Credentials = btoa(`${username}:${password}`)
    // const urlWithCredentials = `${url}?username=${username}&password=${password}`

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
          // Authorization: `Basic ${urlWithCredentials}`,
          // mode: 'cors'
          // credentials: 'include'
        },
        body: JSON.stringify(data)
      })
      if (response.ok) {
        const responseData: User = await response.json()
        setUser(responseData)
        router.push('/home')
        setUser(responseData)
        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={`flex h-full flex-col items-center justify-between lg:px-96 lg:pb-24 px-5 py-7`}>
        <div className="md:w-[480px] w-[350px] ">
          <form onSubmit={handleSubmit(onSubmit)} className="bg-white shadow-md rounded px-8 pt-6 pb-8 ">
            <div>
              <h5>{t('common:login')}</h5>
              <span className="md:text-xs text-[10px]">{t('common:accesoControl')}</span>
            </div>
            <div className="my-4">
              <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
                {t('common:emailOrUsername')}
              </label>
              <input
                className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-1 leading-tight focus:outline-1 focus:shadow-outline"
                id="username"
                type="text"
                placeholder={t('common:enterYourEmail')}
                {...register('username')}
              />
              {errors.username?.message && <ErrorSpan>{errors.username?.message}</ErrorSpan>}
            </div>
            <div className="mb-6">
              <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
                {t('common:password')}
              </label>
              <input
                className="shadow appearance-none border  rounded w-full py-2 px-3 text-gray-700 mb-1 leading-tight focus:outline-1 focus:shadow-outline "
                id="password"
                type="password"
                placeholder={t('common:password')}
                {...register('password', { required: true })}
              />
              {errors.password?.message && <ErrorSpan>{errors.password?.message}</ErrorSpan>}
            </div>
            <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 mb-4"
                type="submit"
              >
                {t('common:login')}
              </button>
              <a className="inline-block align-baseline font-bold text-xs text-gray-950 hover:text-blue-800" href="#">
                {t('common:forgotLogin')}
              </a>
            </div>
          </form>
        </div>
      </main>
    </div>
  )
}
