"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { useLogin } from "@/hooks/useLogin";
import { ApiError } from "@/hooks/api-error";
import { setStoredUser } from "@/lib/auth-user";
import type { LoginUser } from "@/services/login-user";
import { FormField, CheckIcon, SpinnerIcon } from "@/components/auth-form-ui";
import { GoogleSignInButton } from "@/components/google-signin-button";

type Fields = {
  email: string;
  password: string;
};

type FieldErrors = Partial<Record<keyof Fields, string>>;

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Only follow internal, absolute paths after login — block protocol-relative
// ("//evil.com") and external URLs to avoid an open redirect. Read at navigation
// time from window.location (client-only) so the page stays statically rendered.
function safeRedirectTarget(): string {
  if (typeof window === "undefined") return "/dashboard";
  const raw = new URLSearchParams(window.location.search).get("redirect");
  if (!raw || !raw.startsWith("/") || raw.startsWith("//")) return "/dashboard";
  return raw;
}

function validate(values: Fields): FieldErrors {
  const errors: FieldErrors = {};

  if (!values.email.trim()) errors.email = "Please enter your email.";
  else if (!EMAIL_RE.test(values.email.trim()))
    errors.email = "Enter a valid email address.";

  if (!values.password) errors.password = "Please enter your password.";

  return errors;
}

export function LoginForm({
  className,
  ...props
}: React.ComponentProps<"div">) {
  const router = useRouter();
  const { mutate, isPending } = useLogin();

  const [values, setValues] = useState<Fields>({ email: "", password: "" });
  const [errors, setErrors] = useState<FieldErrors>({});
  const [showPassword, setShowPassword] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  function update<K extends keyof Fields>(key: K, value: string) {
    setValues((v) => ({ ...v, [key]: value }));
    setErrors((e) => (e[key] ? { ...e, [key]: undefined } : e));
    setFormError(null);
  }

  // Shared tail of both sign-in paths (password and Google). Tokens are already
  // set as httpOnly cookies by the route handler; cache the (non-sensitive)
  // user so the dashboard can greet them instantly.
  function completeLogin(user: LoginUser | undefined) {
    setStoredUser(user);
    setSuccess(true);
    const target = safeRedirectTarget();
    setTimeout(() => router.push(target), 1100);
  }

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setFormError(null);

    const nextErrors = validate(values);
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;

    mutate(
      { email: values.email.trim(), password: values.password },
      {
        onSuccess: (data) => completeLogin(data?.data?.user),
        onError: (err) => {
          if (err instanceof ApiError) {
            setFormError(
              err.code === 401
                ? "Incorrect email or password."
                : err.message,
            );
          } else {
            setFormError(
              "Couldn't reach the server. Check your connection and try again.",
            );
          }
        },
      },
    );
  }

  if (success) {
    return (
      <div className={cn("glass rounded-3xl p-8 text-center sm:p-10", className)}>
        <div className="mx-auto mb-5 flex h-14 w-14 items-center justify-center rounded-2xl bg-success/15 text-success">
          <CheckIcon />
        </div>
        <h2 className="text-2xl font-bold text-white">Welcome back</h2>
        <p className="mt-2 text-sm text-white/60">
          You&apos;re signed in. Taking you to your dashboard…
        </p>
      </div>
    );
  }

  return (
    <div className={cn("glass rounded-3xl p-7 sm:p-9", className)} {...props}>
      {/* Heading */}
      <div className="mb-7">
        <h1 className="text-2xl font-bold leading-tight text-white sm:text-3xl">
          Welcome back to <span className="text-gradient">VehCall</span>
        </h1>
        <p className="mt-2 text-sm text-white/55">
          Log in to manage your vehicles and stay reachable — privately.
        </p>
      </div>

      <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-5">
        <FormField
          id="email"
          label="Email address"
          type="email"
          autoComplete="email"
          placeholder="you@example.com"
          value={values.email}
          onChange={(v) => update("email", v)}
          error={errors.email}
        />

        <FormField
          id="password"
          label="Password"
          type={showPassword ? "text" : "password"}
          autoComplete="current-password"
          placeholder="Enter your password"
          value={values.password}
          onChange={(v) => update("password", v)}
          error={errors.password}
          toggle={{
            shown: showPassword,
            onToggle: () => setShowPassword((s) => !s),
          }}
        />

        {/* Server / network error */}
        {formError && (
          <div
            role="alert"
            className="rounded-xl border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger"
          >
            {formError}
          </div>
        )}

        <button
          type="submit"
          disabled={isPending}
          className="btn-primary mt-1 w-full disabled:cursor-not-allowed disabled:opacity-70"
        >
          {isPending ? (
            <>
              <SpinnerIcon /> Signing in…
            </>
          ) : (
            "Log in"
          )}
        </button>
      </form>

      <div className="mt-6">
        <GoogleSignInButton
          text="signin_with"
          onSuccess={completeLogin}
          onError={setFormError}
        />
      </div>

      <p className="mt-6 text-center text-sm text-white/55">
        Don&apos;t have an account?{" "}
        <Link
          href="/register"
          className="font-semibold text-brand hover:underline"
        >
          Sign up
        </Link>
      </p>
    </div>
  );
}
