"use client";

import { useState, type FormEvent, type InputHTMLAttributes } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { api, authToken } from "@/lib/api";

export function AuthForm({ mode }: { mode: "login" | "signup" }) {
  const router = useRouter();
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);
  const isSignup = mode === "signup";

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    setPending(true);
    const data = new FormData(event.currentTarget);
    try {
      const email = String(data.get("email"));
      const password = String(data.get("password"));
      const [firstName, ...lastNameParts] = String(data.get("name") ?? "").trim().split(/\s+/);
      const result = isSignup
        ? await api.signup({ firstName, lastName: lastNameParts.join(" ") || undefined, email, password })
        : await api.login({ email, password });
      authToken.set(result.accessToken);
      router.push("/dashboard");
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Unable to continue. Please try again.");
    } finally {
      setPending(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="mt-8 grid gap-5">
      {isSignup && <Field label="Full name" name="name" type="text" autoComplete="name" placeholder="Alex Morgan" />}
      <Field label="Email address" name="email" type="email" autoComplete="email" placeholder="you@example.com" />
      <Field label="Password" name="password" type="password" autoComplete={isSignup ? "new-password" : "current-password"} placeholder="At least 8 characters" minLength={8} />
      {error && <p role="alert" className="rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">{error}</p>}
      <button disabled={pending} className="rounded-xl bg-gradient-ember px-5 py-3.5 font-bold text-white shadow-ember disabled:opacity-60">
        {pending ? "Please wait…" : isSignup ? "Create my account" : "Log in"}
      </button>
      <p className="text-center text-sm text-muted-foreground">
        {isSignup ? "Already a member?" : "New to Encostay?"}{" "}
        <Link href={isSignup ? "/login" : "/signup"} className="font-bold text-ember">{isSignup ? "Log in" : "Create an account"}</Link>
      </p>
    </form>
  );
}

type FieldProps = InputHTMLAttributes<HTMLInputElement> & { label: string; name: string };
function Field({ label, ...props }: FieldProps) {
  return <label className="grid gap-2 text-sm font-bold">{label}<input required {...props} className="rounded-xl border border-input bg-white px-4 py-3 font-normal outline-none transition focus:border-ember focus:ring-3 focus:ring-ember/15" /></label>;
}
