import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { LogIn, Loader2, ShieldCheck } from "lucide-react";
import { useToast } from "@/shared";
import { getErrorMessage } from "@/shared/utils/handleApiError";
import { login as apiLogin, type AuthResponse } from "@/api";

type Props = {
  onLogin: (response: AuthResponse) => void;
};

const AuthPage: React.FC<Props> = ({ onLogin }) => {
  const navigate = useNavigate();
  const { success: toastSuccess, error: toastError, info: toastInfo } = useToast();

  // Login form
  const [loginUsername, setLoginUsername] = useState("");
  const [loginPassword, setLoginPassword] = useState("");
  const [loginLoading, setLoginLoading] = useState(false);
  const [loginError, setLoginError] = useState<string | null>(null);

  // Handle login
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!loginUsername || !loginPassword) return;

    setLoginLoading(true);
    setLoginError(null);
    toastInfo("Logging in...", { title: "Login", durationMs: 1200 });

    try {
      const response = await apiLogin({ username: loginUsername, password: loginPassword });
      
      // JWT 格式: { access_token, refresh_token, username, ... }
      toastSuccess(`Welcome, ${response.username}!`);
      onLogin(response);
      navigate("/home", { replace: true });
    } catch (err: unknown) {
      const raw = err as any;
      const msg = raw?.message?.includes("Failed to fetch")
        ? "Network or CORS error: Please check backend CORS or use Vite proxy in development."
        : getErrorMessage(err, "Login failed. Please try again later.");

      setLoginError(msg);
      toastError(msg);
    } finally {
      setLoginLoading(false);
    }
  };

  return (
    <div className="relative min-h-screen bg-slate-50 text-slate-900 flex items-center justify-center px-4 sm:px-6">
      <div className="pointer-events-none absolute inset-0 bg-app-gradient opacity-90" aria-hidden="true" />
      <div className="relative w-full max-w-md p-6 sm:p-7 bg-white/95 border border-slate-200 rounded-lg shadow-2xl backdrop-blur-xl">
        <div className="animate-fadeIn">
            <header className="mb-6 text-center">
              <ShieldCheck className="w-11 h-11 text-blue-600 mx-auto mb-3" />
              <h1 className="text-2xl font-semibold text-slate-900">OCDP Console</h1>
              <p className="text-slate-600 text-sm mt-1">Sign in with an account created by an administrator</p>
            </header>

            <form onSubmit={handleLogin} className="space-y-4">
              <div>
                <label className="block text-sm text-slate-600">Username</label>
                <input
                  value={loginUsername}
                  onChange={(e) => setLoginUsername(e.target.value)}
                  className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
                  autoComplete="username"
                  required
                />
              </div>

              <div>
                <label className="block text-sm text-slate-600">Password</label>
                <input
                  type="password"
                  value={loginPassword}
                  onChange={(e) => setLoginPassword(e.target.value)}
                  className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
                  autoComplete="current-password"
                  required
                />
              </div>

              <button
                type="submit"
                disabled={loginLoading}
                className={`w-full disabled:opacity-60 font-semibold py-2.5 rounded-lg flex items-center justify-center gap-2 transition-colors duration-150
                  ${loginLoading ? "bg-blue-500 cursor-wait text-white" : "bg-blue-600 text-white hover:bg-blue-700"}`}
              >
                {loginLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogIn className="w-4 h-4" />}
                {loginLoading ? "Logging in..." : "Login"}
              </button>

              {loginError && <p className="text-red-400 text-center text-sm">{loginError}</p>}
            </form>
        </div>
      </div>
    </div>
  );
};

export default AuthPage;
