import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useAuth } from "../context/AuthContext";

export default function LoginPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const { login, isAuthenticated, error, clearError } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  // Get the redirect path from state, or default to "/"
  const from = (location.state as any)?.from?.pathname || "/";

  // Redirect if already logged in
  useEffect(() => {
    if (isAuthenticated) {
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, from]);

  // Clear errors when inputs change
  useEffect(() => {
    if (error) {
      clearError();
    }
  }, [username, password]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!username.trim() || !password.trim()) {
      return;
    }

    setIsSubmitting(true);
    
    try {
      await login(username, password);
      navigate(from, { replace: true });
    } catch {
      // Error is handled by AuthContext
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="bf-login-page">
      <div className="bf-login-container">
        {/* Logo/Brand */}
        <div className="bf-login-header">
          <h1 className="bf-login-brand">
            Brace<span className="bf-brand-accent">iQ</span>
          </h1>
          <p className="bf-login-subtitle">Sign in to your account</p>
        </div>

        {/* Login Form */}
        <form className="bf-login-form" onSubmit={handleSubmit}>
          {error && (
            <div className="bf-login-error">
              {error}
            </div>
          )}

          <div className="bf-form-group">
            <label htmlFor="username" className="bf-form-label">
              Username
            </label>
            <input
              id="username"
              type="text"
              className="bf-form-input"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Enter your username"
              autoComplete="username"
              autoFocus
              disabled={isSubmitting}
            />
          </div>

          <div className="bf-form-group">
            <label htmlFor="password" className="bf-form-label">
              Password
            </label>
            <input
              id="password"
              type="password"
              className="bf-form-input"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
              autoComplete="current-password"
              disabled={isSubmitting}
            />
          </div>

          <button
            type="submit"
            className="bf-login-btn"
            disabled={isSubmitting || !username.trim() || !password.trim()}
          >
            {isSubmitting ? (
              <>
                <span className="bf-login-spinner"></span>
                Signing in...
              </>
            ) : (
              "Sign In"
            )}
          </button>
        </form>

      </div>
    </div>
  );
}
