import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../app/context/AuthProvider';
import { isTestMode } from '../conf/config';

export default function LoginPage() {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('admin123');
  const [error, setError] = useState('');
  const { login, isAuthenticated } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (isTestMode && isAuthenticated) {
      navigate('/', { replace: true });
      return;
    }
  }, [isTestMode, isAuthenticated, navigate]);

  const onSubmit = async (e) => {
    e.preventDefault();
    try {
      await login(username, password);
      navigate('/tasks');
    } catch (err) {
      setError('Неверный логин или пароль');
    }
  };

  return (
    <div className="flex items-center justify-center min-h-screen">
      <div className="p-6 max-w-sm w-full">
        <h2 className="text-2xl font-bold mb-4 text-center">Вход</h2>
        {error && <div className="alert alert-error mb-3">{error}</div>}
        <form onSubmit={onSubmit} className="flex flex-col gap-3">
          <input
            className="input input-bordered"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="Username"
          />
          <input
            className="input input-bordered"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Password"
          />
          <button className="btn btn-primary" type="submit">
            Войти
          </button>
        </form>
      </div>
    </div>
  );
}
