'use client'

import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useRouter } from 'next/navigation'
import useUserStore from '@/app/store/userStore'
import Loader from '@/components/ui/Loader'
import { useForm } from '@/app/hooks/useForm'
import Button from '@/components/ui/Button'
import showToast from '@/components/ui/ShowToast'
import { signIn } from 'next-auth/react'
import TextInput from '@/components/ui/TextInput'
import RoleSelector from '@/components/selectors/RoleSelector'

const validationRules = {
  login: { required: true },
  password: { required: true },
}

const LoginPage = () => {
  const router = useRouter()
  const { isAuthenticated } = useUserStore()
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // проверяем логин
    if (isAuthenticated) {
      // распределяем
      router.replace('/objects')
      return
    }

    const timer = setTimeout(() => {
      setIsLoading(false)
    }, 300)

    return () => clearTimeout(timer)
  }, [isAuthenticated, router])

  const { values, isVisible, handleChange, handleSubmit, togglePasswordVisibility } = useForm(
    {
      login: '',
      password: '',
      role: '',
    },
    validationRules,
    async values => {
      try {
        const result = await signIn('credentials', {
          login: values.login,
          password: values.password,
          redirect: false,
        })

        if (result?.error) {
          showToast({ type: 'error', message: result.error })
          return
        }

        showToast({ type: 'success', message: 'Авторизация успешна!' })
        router.push('/objects')
      } catch {
        showToast({ type: 'error', message: 'Ошибка при входе в аккаунт' })
      }
    }
  )

  if (isLoading) {
    return <Loader />
  }

  return (
    <div className="relative flex h-screen flex-col items-center justify-center gap-8 py-8">
      <div className="mb-4 flex items-center justify-center gap-4">
        <Image
          src="/icons/logo.svg"
          alt="AerBIM Logo"
          width={83}
          height={57}
          className="h-14 w-auto"
        />
        <div className="flex flex-col items-start justify-center">
          <span className="text-xl font-semibold">AerBIM Monitor</span>
          <span className="text-blue text-lg">AMS HT Viewer</span>
        </div>
      </div>
      <div className="bg-cards z-10 mx-4 flex w-full max-w-xl flex-col gap-4 rounded-2xl p-6 shadow-lg md:mx-8">
        <form
          className="flex flex-col items-center justify-between gap-8 md:flex-row md:gap-4"
          onSubmit={handleSubmit}
        >
          <div className="flex w-full flex-col gap-4">
            <h1 className="text-2xl font-bold">Авторизация</h1>
            <TextInput
              value={values.login}
              name="login"
              handleChange={handleChange}
              placeholder="ivan_ivanov"
              style="register"
              label="Ваш логин"
            />

            <TextInput
              value={values.password}
              name="password"
              handleChange={handleChange}
              placeholder="Не менее 8 символов"
              style="register"
              label="Ваш пароль"
              isPassword={true}
              isVisible={isVisible}
              togglePasswordVisibility={togglePasswordVisibility}
            />
            <RoleSelector
              value={values.role}
              name="role"
              handleChange={handleChange}
              label="Ваша роль"
              placeholder="Выберите вашу роль"
            />

            <div className="flex w-full items-center justify-center pt-6">
              <Button
                text="Войти"
                className="bg-blue mt-3 flex w-full items-center justify-center py-4 text-base font-semibold text-white shadow-lg transition-all duration-200 hover:opacity-90"
                type="submit"
              />
            </div>
          </div>
        </form>

        <p className="text-center text-base font-medium">
          <span className="hover:text-blue transition-colors duration-200 hover:underline">
            <Link href="/password-recovery">Забыли логин/пароль?</Link>
          </span>
        </p>
      </div>
    </div>
  )
}

export default LoginPage
