import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { LogIn, Loader2, ShieldCheck, UserPlus } from "lucide-react";
import { useToast } from "@/shared";
import { getErrorMessage } from "@/shared/utils/handleApiError";
import { login as apiLogin, fetchAuthStatus, setupInitialAdmin, 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();

  // Auth status
  const [needsSetup, setNeedsSetup] = useState<boolean | null>(null);
  const [checkingStatus, setCheckingStatus] = useState(true);

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

  // Setup form
  const [setupUsername, setSetupUsername] = useState("");
  const [setupPassword, setSetupPassword] = useState("");
  const [setupEmail, setSetupEmail] = useState("");
  const [setupLoading, setSetupLoading] = useState(false);
  const [setupError, setSetupError] = useState<string | null>(null);

  // Check if setup is needed on mount
  useEffect(() => {
    let cancelled = false;
    fetchAuthStatus()
      .then((status) => {
        if (!cancelled) {
          setNeedsSetup(status.needsSetup);
          setCheckingStatus(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setNeedsSetup(false); // fall back to login on error
          setCheckingStatus(false);
        }
      });
    return () => { cancelled = true; };
  }, []);

  // Handle setup (first admin registration)
  const handleSetup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!setupUsername || !setupPassword) return;

    setSetupLoading(true);
    setSetupError(null);
    toastInfo("Creating admin account...", { title: "Setup", durationMs: 1200 });

    try {
      const result = await setupInitialAdmin({
        username: setupUsername,
        password: setupPassword,
        email: setupEmail || undefined,
      });

      // setupInitialAdmin returns tokens — use them directly to avoid redundant login
      onLogin({
        accessToken: result.accessToken,
        refreshToken: result.refreshToken,
        username: setupUsername,
      } as any);

      toastSuccess("Admin account created. Welcome!");
      navigate("/home", { replace: true });
    } catch (err: unknown) {
      const msg = getErrorMessage(err, "Setup failed. Please try again later.");
      setSetupError(msg);
      toastError(msg);
    } finally {
      setSetupLoading(false);
    }
  };

  // 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 });
      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);
    }
  };

  if (checkingStatus) {
    return (
      <div className="relative min-h-screen bg-slate-50 flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
      </div>
    );
  }

  // Setup view — first admin registration
  if (needsSetup) {
    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-emerald-600 mx-auto mb-3" />
              <h1 className="text-2xl font-semibold text-slate-900">OCDP Initial Setup</h1>
              <p className="text-slate-600 text-sm mt-1">Create the first administrator account to get started.</p>
            </header>

            <form onSubmit={handleSetup} className="space-y-4">
              <div>
                <label className="block text-sm text-slate-600">Admin Username</label>
                <input
                  value={setupUsername}
                  onChange={(e) => setSetupUsername(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-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
                  autoComplete="username"
                  autoFocus
                  required
                />
              </div>

              <div>
                <label className="block text-sm text-slate-600">Password</label>
                <input
                  type="password"
                  value={setupPassword}
                  onChange={(e) => setSetupPassword(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-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
                  autoComplete="new-password"
                  required
                />
              </div>

              <div>
                <label className="block text-sm text-slate-600">Email (optional)</label>
                <input
                  type="email"
                  value={setupEmail}
                  onChange={(e) => setSetupEmail(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-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
                  autoComplete="email"
                  placeholder="admin@example.com"
                />
              </div>

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

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

  // Regular login view
  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;
