"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

import { apiPost } from "@/lib/api";

export function AuthForm({ mode }: { mode: "login" | "register" }) {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async (event: React.FormEvent) => {
    event.preventDefault();
    setBusy(true);
    setError("");

    try {
      const path = mode === "login" ? "/api/auth/login" : "/api/auth/register";
      await apiPost(path, { email, password });
      if (mode === "register") {
        await apiPost("/api/auth/login", { email, password });
      }
      router.push("/dashboard");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Request failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="shell flex min-h-screen items-center justify-center py-14">
      <section className="panel w-full max-w-md p-8 sm:p-10">
        <div className="mb-8">
          <p className="eyebrow">Animatrix</p>
          <h1 className="mt-3 text-3xl font-semibold text-white">
            {mode === "login" ? "Sign in" : "Create account"}
          </h1>
          <p className="mt-3 text-sm leading-6 text-subtext">
            {mode === "login"
              ? "Use your workspace account to open the generator."
              : "Create a local account for this workspace."}
          </p>
        </div>

        <form className="space-y-4" onSubmit={submit}>
          <input
            autoComplete="email"
            className="input"
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
          <input
            autoComplete={mode === "login" ? "current-password" : "new-password"}
            className="input"
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          {error ? (
            <div className="rounded-2xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">
              {error}
            </div>
          ) : null}
          <button className="btn-primary w-full" disabled={busy} type="submit">
            {busy ? "Working..." : mode === "login" ? "Sign in" : "Create account"}
          </button>
        </form>

        <div className="mt-6 text-sm text-subtext">
          {mode === "login" ? (
            <>
              No account yet? <Link className="text-accent" href="/register">Register</Link>
            </>
          ) : (
            <>
              Already registered? <Link className="text-accent" href="/login">Sign in</Link>
            </>
          )}
        </div>
      </section>
    </div>
  );
}
