"use client";

import { useState } from "react";

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

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setPending(true);
    const form = new FormData(e.currentTarget);
    const payload = Object.fromEntries(form.entries());
    const res = await fetch(mode === "login" ? "/api/auth/login" : "/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const json = await res.json();
    setPending(false);
    if (!res.ok) {
      setError(json.error || "Something went wrong");
      return;
    }
    const requested = new URLSearchParams(window.location.search).get("next");
    const next =
      requested && requested.startsWith("/") && !requested.startsWith("//")
        ? requested
        : json.next || "/dashboard";
    window.location.assign(next);
  }

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      {mode === "register" ? (
        <>
          <label className="block text-sm">
            Full name
            <input
              required
              name="name"
              className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 outline-none ring-gold focus:ring-2"
            />
          </label>
          <label className="block text-sm">
            Phone (MoMo)
            <input
              name="phone"
              placeholder="024…"
              className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 outline-none ring-gold focus:ring-2"
            />
          </label>
        </>
      ) : null}
      <label className="block text-sm">
        Email
        <input
          required
          type="email"
          name="email"
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 outline-none ring-gold focus:ring-2"
        />
      </label>
      <label className="block text-sm">
        Password
        <input
          required
          type="password"
          name="password"
          minLength={8}
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 outline-none ring-gold focus:ring-2"
        />
      </label>
      {error ? <p className="text-sm text-terra">{error}</p> : null}
      <button
        disabled={pending}
        className="w-full rounded-full bg-forest py-3 text-sm font-semibold text-gold-2 disabled:opacity-60"
      >
        {pending ? "Please wait…" : mode === "login" ? "Sign in" : "Register"}
      </button>
    </form>
  );
}
