"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useAuthActions } from "@convex-dev/auth/react";
import { useConvex } from "convex/react";
import { Eye, EyeOff, LogIn } from "lucide-react";
import { api } from "../../../../convex/_generated/api";
import { recordLoginAction, recordFailedLoginAction } from "./actions";
import { Button } from "@/components/ui/button";
import { Input, Field } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/primitives";

export function LoginForm({ next }: { next?: string }) {
  const { signIn } = useAuthActions();
  const convex = useConvex();
  const router = useRouter();
  const [show, setShow] = React.useState(false);
  const [pending, setPending] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const identifier = String(fd.get("identifier") ?? "").trim();
    const password = String(fd.get("password") ?? "");
    if (!identifier || !password) return setError("Enter your email and password.");
    setPending(true);
    setError(null);
    try {
      const email = await convex.query(api.security.emailForIdentifier, { identifier });
      if (!email) {
        await recordFailedLoginAction(identifier.toLowerCase(), "Unknown account");
        setError("Incorrect email/username or password.");
        return;
      }
      const throttle = await convex.query(api.security.loginThrottle, { email });
      if (throttle.blocked) return setError(`Too many attempts. Please wait ${Math.ceil(throttle.retryAfterSeconds / 60)} minute${throttle.retryAfterSeconds > 60 ? "s" : ""} and try again.`);
      try {
        await signIn("password", { email, password, flow: "signIn" });
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        await recordFailedLoginAction(email, /disabled|inactive|suspended/i.test(msg) ? "Account disabled" : "Invalid password");
        setError(/disabled|inactive|suspended/i.test(msg) ? "This account is disabled. Contact the administrator." : "Incorrect email/username or password.");
        return;
      }
      await recordLoginAction();
      const target = next && next.startsWith("/") && !next.startsWith("//") ? next : "/dashboard";
      router.replace(target);
      router.refresh();
    } finally {
      setPending(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="mt-8 space-y-5">
      <Field label="Email or username" htmlFor="identifier" required>
        <Input id="identifier" name="identifier" autoComplete="username" placeholder="you@locajour.ma" required autoFocus className="h-11" />
      </Field>
      <Field label="Password" htmlFor="password" required>
        <div className="relative">
          <Input id="password" name="password" type={show ? "text" : "password"} autoComplete="current-password" placeholder="••••••••" required className="h-11 pr-11" />
          <button type="button" onClick={() => setShow((s) => !s)} className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-fg-subtle hover:bg-surface-2 hover:text-fg" aria-label={show ? "Hide password" : "Show password"}>
            {show ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
      </Field>
      <div className="flex items-center justify-between">
        <label className="flex cursor-pointer items-center gap-2 text-sm text-fg-muted">
          <Checkbox name="remember" defaultChecked />
          Remember me
        </label>
        <Link href="/forgot-password" className="text-sm font-medium text-primary hover:underline">
          Forgot password?
        </Link>
      </div>
      {error ? (
        <div role="alert" className="rounded-md border border-negative-500/25 bg-negative-50 px-3 py-2 text-sm text-negative-700 dark:bg-negative-500/10">
          {error}
        </div>
      ) : null}
      <Button type="submit" size="xl" className="w-full" loading={pending}>
        <LogIn /> Sign in
      </Button>
    </form>
  );
}
