import { FC, FormEvent, useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { login } from './authService'

const LoginPage: FC = () => {
  const [password, setPassword] = useState('')
  const [error, setError] = useState(false)
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(false)
    setLoading(true)

    const success = await login(password)
    setLoading(false)

    if (success) {
      navigate('/templates', { replace: true })
    } else {
      setError(true)
      setPassword('')
    }
  }

  return (
    <div className="flex h-screen items-center justify-center bg-gray-50">
      <form
        onSubmit={handleSubmit}
        className="w-full max-w-sm rounded-lg bg-white p-8 shadow-md"
      >
        <h1 className="mb-6 text-center text-xl font-semibold text-gray-800">
          Вход в режим администратора
        </h1>

        <input
          type="password"
          value={password}
          onChange={e => setPassword(e.target.value)}
          placeholder="Пароль"
          className={`mb-4 w-full rounded border px-4 py-2 outline-none focus:ring-2 ${
            error
              ? 'border-red-400 focus:ring-red-300'
              : 'border-gray-300 focus:ring-blue-300'
          }`}
          autoFocus
        />

        {error && (
          <p className="mb-4 text-sm text-red-500">Неверный пароль</p>
        )}

        <button
          type="submit"
          disabled={loading || !password}
          className="w-full rounded bg-blue-600 px-4 py-2 text-white transition hover:bg-blue-700 disabled:opacity-50"
        >
          {loading ? 'Проверка...' : 'Войти'}
        </button>
      </form>
    </div>
  )
}

export default LoginPage
