"use client";

import { cn } from "@/lib/utils";
import { FormEvent, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, Loader2, X } from "lucide-react";
import { validateEmail, validatePassword, clearFieldError } from "@/utils/form-validation";

export function LoginForm({
  className,
  ...props
}: React.ComponentProps<"form">) {
  const router = useRouter();
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<
    Partial<Record<"email" | "password", string>>
  >({});
  const [showPassword, setShowPassword] = useState(false);
  const [redirectingToAddSubdomain, setRedirectingToAddSubdomain] = useState(false);
  const [verifyingImpersonate, setVerifyingImpersonate] = useState(false);

  // Apex oxyworkspace.com: redirect /login to /signin_step (same as middleware)
  useEffect(() => {
    if (typeof window === "undefined") return;
    const hostname = window.location.hostname ?? "";
    const normalized = hostname.replace(/^www\./i, "");
    if (normalized === "oxyfinz.com") {
      setRedirectingToAddSubdomain(true);
      router.replace("/signin_step");
      return;
    }
  }, [router]);

  // Impersonation: handle #token=<jwt> in URL hash
  useEffect(() => {
    if (typeof window === "undefined") return;
    const hash = window.location.hash;
    if (!hash.startsWith("#token=")) return;

    const token = hash.slice("#token=".length);
    if (!token) return;

    // Clear the hash immediately so the token is no longer in the URL
    window.history.replaceState(null, "", window.location.pathname + window.location.search);

    setVerifyingImpersonate(true);

    fetch("/api/verify-impersonate-token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token }),
      credentials: "include",
    })
      .then(async (res) => {
        if (!res.ok) {
          const body = await res.json().catch(() => ({}));
          setErrorMsg(body?.error ?? "Impersonation login failed. The link may have expired.");
          setVerifyingImpersonate(false);
          return;
        }
        router.replace("/dashboard");
        router.refresh();
      })
      .catch(() => {
        setErrorMsg("Unexpected error during impersonation login.");
        setVerifyingImpersonate(false);
      });
  }, [router]);

  const handleClearFieldError = (field: "email" | "password") => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setErrorMsg(null);

    const formData = new FormData(event.currentTarget);
    const email = String(formData.get("email") ?? "").trim();
    const password = String(formData.get("password") ?? "").trim();

    const nextFieldErrors: Partial<Record<"email" | "password", string>> = {};

    const emailError = validateEmail(email);
    if (emailError) nextFieldErrors.email = emailError;

    const passwordError = validatePassword(password);
    if (passwordError) nextFieldErrors.password = passwordError;

    if (Object.keys(nextFieldErrors).length > 0) {
      setFieldErrors(nextFieldErrors);
      return;
    }

    setFieldErrors({});
    setLoading(true);

    try {
      const payload = new FormData();
      payload.append("username", email);
      payload.append("password", password);

      const response = await fetch(`/api/login`, {
        method: "POST",
        body: payload,
        credentials: "include",
        headers: { Accept: "application/json" },
      });

      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          setErrorMsg("Username and password is incorrect");
          return;
        }

        const contentType = response.headers.get("content-type") ?? "";
        let upstreamMessage: string | null = null;

        if (contentType.includes("application/json")) {
          const body = await response.json().catch(() => null);
          upstreamMessage =
            typeof body?.error === "string"
              ? body.error
              : typeof body?.message === "string"
              ? body.message
              : null;
        } else {
          const text = await response.text().catch(() => "");
          upstreamMessage = text.trim() || null;
        }

        const fallbackMessage =
          response.status >= 500
            ? "Authentication service is unavailable. Please try again later."
            : "Invalid credentials. Please double-check your email and password.";

        setErrorMsg(upstreamMessage || fallbackMessage);
        return;
      }

      await response.json().catch(() => ({}));
      let redirectPath = "/dashboard";

      if (typeof window !== "undefined") {
        const params = new URLSearchParams(window.location.search);
        const fromParam = params.get("from");
        if (fromParam) {
          try {
            // Resolve against current origin and verify it stays on the same origin.
            // This rejects //evil.com, /\evil.com, javascript:, data:, and any
            // URL-encoded variants that browsers would normalize to an external host.
            const resolved = new URL(fromParam, window.location.origin);
            if (resolved.origin === window.location.origin) {
              redirectPath = fromParam;
            }
          } catch {
            // Malformed URL — keep default /dashboard redirect
          }
        }
      }

      router.replace(redirectPath);
      router.refresh();
    } catch (err: any) {
      console.error("Unexpected error:", err);
      setErrorMsg("Unexpected error connecting to server.");
    } finally {
      setLoading(false);
    }
  }

  if (redirectingToAddSubdomain || verifyingImpersonate) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-8">
        <Loader2 className="h-6 w-6 animate-spin text-[hsl(var(--primary))]" />
        <p className="text-sm text-[hsl(var(--muted-foreground))]">
          {verifyingImpersonate ? "Signing in…" : "Redirecting..."}
        </p>
      </div>
    );
  }

  return (
    <form
      className={cn("flex flex-col gap-5", className)}
      {...props}
      noValidate
      onSubmit={handleSubmit}
    >
      {errorMsg ? (
        <div className="flex items-start justify-between gap-3 rounded-lg border border-[hsl(var(--destructive))]/25 bg-[hsl(var(--destructive))]/10 px-4 py-3">
          <p role="alert" className="text-sm text-[hsl(var(--destructive))]">
            {errorMsg}
          </p>
          <button
            type="button"
            onClick={() => setErrorMsg(null)}
            aria-label="Dismiss"
            className="text-[hsl(var(--destructive))]/70 transition-colors hover:text-[hsl(var(--destructive))]"
          >
            <X className="size-4" />
          </button>
        </div>
      ) : null}

      <div className="flex flex-col gap-2">
        <label htmlFor="email" className="immersive-label">
          Email
        </label>
        <input
          id="email"
          type="email"
          name="email"
          placeholder="you@example.com"
          required
          disabled={loading}
          aria-invalid={Boolean(fieldErrors.email)}
          onInput={() => handleClearFieldError("email")}
          autoComplete="email"
          className={cn(
            "w-full border-b border-white/10 bg-transparent pb-2.5 text-base text-[hsl(var(--foreground))] outline-none transition-colors placeholder:text-[hsl(var(--muted-foreground))]/60 focus:border-[hsl(var(--primary))]",
            fieldErrors.email && "border-[hsl(var(--destructive))]"
          )}
        />
        {fieldErrors.email && (
          <p className="text-xs text-[hsl(var(--destructive))]">{fieldErrors.email}</p>
        )}
      </div>

      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between">
          <label htmlFor="password" className="immersive-label">
            Password
          </label>
          <a
            href="/forgot_password"
            className="text-xs font-semibold text-[hsl(var(--primary))] underline-offset-4 transition-colors hover:underline"
          >
            Forgot password?
          </a>
        </div>
        <div className="relative">
          <input
            id="password"
            type={showPassword ? "text" : "password"}
            name="password"
            required
            disabled={loading}
            aria-invalid={Boolean(fieldErrors.password)}
            onInput={() => handleClearFieldError("password")}
            autoComplete="current-password"
            className={cn(
              "w-full border-b border-white/10 bg-transparent pb-2.5 pr-9 text-base text-[hsl(var(--foreground))] outline-none transition-colors placeholder:text-[hsl(var(--muted-foreground))]/60 focus:border-[hsl(var(--primary))]",
              fieldErrors.password && "border-[hsl(var(--destructive))]"
            )}
          />
          <button
            type="button"
            onClick={() => setShowPassword((v) => !v)}
            aria-label={showPassword ? "Hide password" : "Show password"}
            aria-pressed={showPassword}
            className="absolute right-0 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center text-[hsl(var(--muted-foreground))] transition-colors hover:text-[hsl(var(--foreground))]"
          >
            {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
        {fieldErrors.password && (
          <p className="text-xs text-[hsl(var(--destructive))]">{fieldErrors.password}</p>
        )}
      </div>

      <button
        type="submit"
        disabled={loading}
        className="group mt-2 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))] disabled:opacity-60"
      >
        {loading ? (
          <>
            <Loader2 className="size-4 animate-spin" />
            Signing in…
          </>
        ) : (
          "Sign in"
        )}
      </button>
    </form>
  );
}
