// @File: src/pages/Login.tsx
// @Desc: Standalone email/password sign-in form styled after the DoItEasy
//        reference mock. Split layout: dark forest-green info panel on the left
//        (white DoItEasy logo + feature bullets with gold checkmarks), clean
//        white panel on the right with the color logo centered above a card
//        containing the email/password form.
//        Credentials are validated via the backend /api/v1/whmcs/login
//        endpoint (which proxies WHMCS ValidateLogin) and the returned token
//        is stored in localStorage.token.
import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  ArrowRight,
  Check,
  Eye,
  EyeOff,
  Loader2,
  Lock,
  LogIn,
  Mail,
  ShieldCheck,
  UserPlus,
} from "lucide-react";
import { client } from "@/lib/api";
import { adminLoginLocal } from "@/lib/adminApi";
import {
  extractErrorMessage,
  fetchMe,
  hasToken,
  setSession,
} from "@/lib/auth";
import SocialLoginButtons from "@/components/auth/SocialLoginButtons";

interface LoginResponseData {
  token: string;
  user_id: string;
  email: string;
  name?: string | null;
  client_id: number;
}

// Design tokens mirrored from the reference mock.
const DESIGN = {
  forestGreen: "#0E5A35",
  forestGreenDark: "#0A4027",
  accentGold: "#F5C23B",
  accentLime: "#22C55E",
  serifFont:
    "'Playfair Display', 'Georgia', 'Times New Roman', serif",
  sansFont:
    "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
};

const FEATURES = [
  "One sign-in for hosting, VPS, domains and tickets",
  "Authenticated directly against your billing system",
  "Secure — your password is never stored on this site",
];

export default function Login() {
  const navigate = useNavigate();

  const [checking, setChecking] = useState(true);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [remember, setRemember] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // If there is already a valid session, skip straight to the dashboard.
  // Also pre-warm the backend container so that when the user submits the
  // form the backend is already awake and won't return the Atoms platform's
  // "503 Temporarily Unavailable" HTML shell during cold start.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      // Fire-and-forget pre-warm ping. Swallow all errors — this is purely
      // to wake the backend up. Retry a couple of times silently for robustness.
      (async () => {
        for (let i = 0; i < 3; i++) {
          try {
            await client.apiCall.invoke({
              url: "/api/v1/whmcs/health",
              method: "GET",
            });
            return;
          } catch {
            // wait a bit and try again
            await new Promise((r) => setTimeout(r, 1000 + i * 1000));
          }
        }
      })();

      if (!hasToken()) {
        if (!cancelled) setChecking(false);
        return;
      }
      const me = await fetchMe();
      if (!cancelled && me) {
        navigate("/client", { replace: true });
        return;
      }
      if (!cancelled) setChecking(false);
    })();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setError(null);

    if (!email.trim()) {
      setError("Please enter your email.");
      return;
    }
    if (!password) {
      setError("Please enter your password.");
      return;
    }

    setSubmitting(true);

    // Auto-retry transient platform errors (503 Temporarily Unavailable, 502,
    // 504, HTML error pages, or raw network errors). The Atoms platform can
    // briefly return its own 503 HTML shell when the backend container is
    // cold-starting — we want the user to succeed on the first click whenever
    // possible, without them needing to hit "Sign In" repeatedly.
    const MAX_ATTEMPTS = 4;
    const BACKOFF_MS = [800, 1800, 3000];

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const isTransientPlatformError = (err: any): boolean => {
      const status: number | undefined =
        err?.response?.status ?? err?.status;
      const rawData = err?.response?.data ?? err?.data;
      const looksLikeHtml =
        typeof rawData === "string" && /<!doctype html|<html/i.test(rawData);
      const msg = String(err?.message ?? "").toLowerCase();
      const isNetwork =
        msg === "network error" ||
        msg.includes("failed to fetch") ||
        msg.includes("timeout") ||
        msg.includes("failed the initial dns") ||
        msg.includes("could not acquire callback lock");
      return (
        status === 502 ||
        status === 503 ||
        status === 504 ||
        looksLikeHtml ||
        isNetwork
      );
    };

    let lastErr: unknown = null;
    for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
      try {
        const res = await client.apiCall.invoke({
          url: "/api/v1/whmcs/login",
          method: "POST",
          data: { email: email.trim().toLowerCase(), password },
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const data: LoginResponseData = (res as any)?.data;
        if (!data?.token) {
          throw new Error("Sign-in response was incomplete. Please try again.");
        }
        setSession({
          token: data.token,
          user_id: data.user_id,
          email: data.email,
          name: data.name ?? null,
          client_id: data.client_id,
        });
        navigate("/client", { replace: true });
        setSubmitting(false);
        return;
      } catch (err) {
        lastErr = err;
        if (isTransientPlatformError(err) && attempt < MAX_ATTEMPTS) {
          // Surface a reassuring message while we silently retry.
          setError(
            "Connecting to the server… this is taking a moment, please wait."
          );
          await new Promise((r) =>
            setTimeout(r, BACKOFF_MS[attempt - 1] ?? 3000)
          );
          continue;
        }
        break;
      }
    }

    // WHMCS sign-in failed (non-transient, or retries exhausted). Fall back to
    // local email/password auth so seeded admins / local-only accounts can
    // still sign in from the main login page. Any error from the local flow is
    // swallowed and the WHMCS error message is kept as the user-facing reason,
    // to avoid leaking which auth backend accepted the email.
    try {
      const local = await adminLoginLocal(email.trim().toLowerCase(), password);
      setSession({
        token: local.token,
        user_id: local.user_id,
        email: local.email,
        name: null,
        client_id: 0,
      });
      // Admins land in the admin dashboard; other local users go to the client area.
      navigate(local.role === "admin" ? "/admin" : "/client", { replace: true });
      setSubmitting(false);
      return;
    } catch {
      // Fall through to surface the original WHMCS error below.
    }

    setError(extractErrorMessage(lastErr, "Invalid email or password."));
    setSubmitting(false);
  };

  const inputBaseClass =
    "w-full pl-10 pr-3 py-3 rounded-lg border border-slate-300 bg-white text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-600 transition";

  // ---------------------------------------------------------------------------
  // Form body (shared between desktop card & mobile layout)
  // ---------------------------------------------------------------------------
  const FormBody = (
    <>
      {checking ? (
        <div className="flex items-center justify-center py-8 text-slate-500">
          <Loader2 className="w-5 h-5 animate-spin mr-2" />
          <span className="text-sm">Checking your session…</span>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <label className="block">
            <span className="text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
              <Mail className="w-3.5 h-3.5" /> Email
            </span>
            <div className="relative">
              <Mail className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type="email"
                autoComplete="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@company.com"
                className={inputBaseClass}
                required
              />
            </div>
          </label>

          <label className="block">
            <span className="text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
              <Lock className="w-3.5 h-3.5" /> Password
            </span>
            <div className="relative">
              <Lock className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type={showPassword ? "text" : "password"}
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                className={`${inputBaseClass} pr-10`}
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword((s) => !s)}
                className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-slate-400 hover:text-slate-600 !bg-transparent hover:!bg-transparent"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {showPassword ? (
                  <EyeOff className="w-4 h-4" />
                ) : (
                  <Eye className="w-4 h-4" />
                )}
              </button>
            </div>
          </label>

          <div className="flex items-center justify-between text-xs">
            <label className="flex items-center gap-2 cursor-pointer text-slate-600">
              <input
                type="checkbox"
                checked={remember}
                onChange={(e) => setRemember(e.target.checked)}
                style={{ accentColor: DESIGN.forestGreen }}
              />
              Keep me signed in
            </label>
            <Link
              to="/forgot"
              className="font-semibold hover:underline"
              style={{ color: DESIGN.forestGreen }}
            >
              Forgot password?
            </Link>
          </div>

          {error && (
            <div className="text-xs text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting}
            className="w-full py-3 rounded-lg text-white font-semibold text-sm transition hover:opacity-95 flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed shadow-sm"
            style={{ backgroundColor: DESIGN.forestGreen }}
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Signing in…
              </>
            ) : (
              <>
                <LogIn className="w-4 h-4" />
                Sign In
                <ArrowRight className="w-4 h-4" />
              </>
            )}
          </button>

          <Link
            to="/register"
            className="w-full py-2.5 rounded-lg border-2 font-semibold text-sm transition flex items-center justify-center gap-2 !bg-transparent hover:!bg-transparent"
            style={{
              borderColor: DESIGN.forestGreen,
              color: DESIGN.forestGreen,
            }}
          >
            <UserPlus className="w-4 h-4" />
            Create a new account
          </Link>

          <SocialLoginButtons mode="login" dividerLabel="or continue with" />

          <div className="flex items-center gap-2 text-[11px] text-slate-400 justify-center pt-1">
            <ShieldCheck className="w-3 h-3" />
            Credentials are validated against the billing system over a secure
            channel.
          </div>

          <p className="text-[11px] text-slate-400 text-center leading-relaxed">
            By continuing you agree to our{" "}
            <Link
              to="/service-terms"
              className="font-semibold hover:underline"
              style={{ color: DESIGN.forestGreen }}
            >
              Service Terms
            </Link>
            ,{" "}
            <Link
              to="/refund-policy"
              className="font-semibold hover:underline"
              style={{ color: DESIGN.forestGreen }}
            >
              Refund Policy
            </Link>
            , and{" "}
            <Link
              to="/privacy-center"
              className="font-semibold hover:underline"
              style={{ color: DESIGN.forestGreen }}
            >
              Privacy
            </Link>
            .
          </p>
        </form>
      )}
    </>
  );

  // ---------------------------------------------------------------------------
  // Layout — split screen: dark green left, white right (matches the mock)
  // ---------------------------------------------------------------------------
  return (
    <div
      className="min-h-screen grid lg:grid-cols-2"
      style={{ fontFamily: DESIGN.sansFont }}
    >
      {/* LEFT: dark forest-green info panel */}
      <div
        className="relative hidden lg:flex flex-col justify-between p-10 xl:p-14 text-white overflow-hidden"
        style={{
          background: `radial-gradient(ellipse at center, ${DESIGN.forestGreen} 0%, ${DESIGN.forestGreenDark} 100%)`,
        }}
      >
        {/* Subtle decorative rings */}
        <div
          aria-hidden
          className="absolute -top-32 -right-32 w-96 h-96 rounded-full opacity-10"
          style={{
            background: `radial-gradient(circle, ${DESIGN.accentGold} 0%, transparent 70%)`,
          }}
        />
        <div
          aria-hidden
          className="absolute -bottom-40 -left-40 w-[500px] h-[500px] rounded-full opacity-10"
          style={{
            background: `radial-gradient(circle, #ffffff 0%, transparent 70%)`,
          }}
        />

        {/* Top: logo */}
        <div className="relative z-10">
          <Link to="/" className="inline-flex items-center">
            <img
              src="/logo.svg"
              alt="DoItEasy"
              className="h-12 md:h-14 w-auto object-contain brightness-0 invert"
              onError={(e) =>
                ((e.target as HTMLImageElement).style.display = "none")
              }
            />
          </Link>
        </div>

        {/* Middle: heading + feature bullets */}
        <div className="relative z-10 max-w-3xl">
          <h2
            className="text-3xl xl:text-4xl font-bold leading-tight mb-4 text-white whitespace-nowrap"
            style={{ fontFamily: DESIGN.serifFont }}
          >
            Welcome back to{" "}
            <span style={{ color: DESIGN.accentGold }}>DoItEasy</span>
          </h2>
          <p className="text-white/80 text-sm xl:text-base mb-8 leading-relaxed whitespace-nowrap">
            Manage hosting, VPS, domains and tickets from one premium dashboard.
          </p>
          <ul className="space-y-4">
            {FEATURES.map((feature) => (
              <li key={feature} className="flex items-start gap-3 text-sm">
                <span
                  className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 mt-0.5 shadow-sm"
                  style={{
                    backgroundColor: DESIGN.accentGold,
                    color: DESIGN.forestGreenDark,
                  }}
                >
                  <Check className="w-3.5 h-3.5" strokeWidth={3.5} />
                </span>
                <span className="text-white/90 leading-relaxed">{feature}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* Bottom: copyright */}
        <div className="relative z-10 text-xs text-white/60">
          © {new Date().getFullYear()} DoItEasy · Trusted by 10,000+
          businesses
        </div>
      </div>

      {/* RIGHT: clean white panel with centered logo + form card */}
      <div className="flex items-center justify-center p-6 md:p-10 bg-white">
        <div className="w-full max-w-md">
          {/* Mobile top bar: show white logo on a green strip so it stays on-brand on small screens */}
          <div
            className="lg:hidden -mx-6 -mt-6 mb-6 px-6 py-5 flex justify-center"
            style={{
              background: `radial-gradient(ellipse at center, ${DESIGN.forestGreen} 0%, ${DESIGN.forestGreenDark} 100%)`,
            }}
          >
            <img
              src="/logo.svg"
              alt="DoItEasy"
              className="h-10 md:h-12 w-auto object-contain brightness-0 invert"
              onError={(e) =>
                ((e.target as HTMLImageElement).style.display = "none")
              }
            />
          </div>

          {/* Centered full-color logo */}
          <div className="flex justify-center mb-6">
            <img
              src="/logo.svg"
              alt="DoItEasy Web Hosting"
              className="h-16 md:h-20 w-auto object-contain"
              onError={(e) =>
                ((e.target as HTMLImageElement).style.display = "none")
              }
            />
          </div>

          {/* Headings */}
          <div className="text-center mb-6">
            <h1
              className="text-3xl md:text-4xl font-bold text-slate-900 mb-2"
              style={{ fontFamily: DESIGN.serifFont }}
            >
              Welcome back
            </h1>
            <p className="text-sm text-slate-500">
              Sign in to manage your services, invoices, domains and tickets.
            </p>
          </div>

          {/* Form card */}
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200/80 p-6 md:p-8">
            {FormBody}
          </div>
        </div>
      </div>
    </div>
  );
}