"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { Reveal } from "../../../components/Reveal";
import { mergeServerCartIntoLocal } from "../../../lib/cart";
import { dispatchAuthChanged } from "../../../lib/auth";

export function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  // WishlistButton (and anything else login-gated) sends the shopper back
  // here with ?redirect=<where they were>, e.g. a product page they
  // wanted to heart — previously ignored, always landing on
  // /konto/bestellungen regardless of where the login was triggered from.
  const redirectTo = searchParams.get("redirect") || "/konto/bestellungen";
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/account/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Login fehlgeschlagen.");
        setLoading(false);
        return;
      }
      await mergeServerCartIntoLocal();
      dispatchAuthChanged();
      router.push(redirectTo);
      router.refresh();
    } catch {
      setError("Login ist gerade nicht möglich.");
      setLoading(false);
    }
  }

  return (
    <Reveal className="flex flex-col gap-6 items-start pt-10 pb-20 px-[var(--layout-padding-x)] w-full max-w-[26rem] mx-auto">
      <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
        Anmelden
      </p>
      <form onSubmit={handleSubmit} className="flex flex-col gap-4 items-start w-full">
        <label className="flex flex-col gap-2 items-start w-full">
          <span className="text-label text-text-muted">E-Mail-Adresse</span>
          <input
            type="email"
            required
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
          />
        </label>
        <label className="flex flex-col gap-2 items-start w-full">
          <span className="text-label text-text-muted">Passwort</span>
          <input
            type="password"
            required
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
          />
        </label>
        {error && <p className="text-label text-red-600">{error}</p>}
        <button
          type="submit"
          disabled={loading}
          className={`w-full flex items-center justify-center py-4 rounded-sm bg-brand hover:bg-brand-hover active:scale-[0.97] transition-all font-bold text-body text-text-primary ${loading ? "opacity-70 pointer-events-none" : ""}`}
        >
          {loading ? "Einen Moment…" : "Einloggen"}
        </button>
      </form>
      <Link href="/konto/passwort-vergessen" className="text-body-sm text-text-muted underline hover:text-brand transition-colors">
        Passwort vergessen?
      </Link>
      <p className="text-body-sm text-text-muted">
        Noch kein Konto?{" "}
        <Link
          href={`/konto/registrieren${redirectTo !== "/konto/bestellungen" ? `?redirect=${encodeURIComponent(redirectTo)}` : ""}`}
          className="underline hover:text-brand transition-colors"
        >
          Jetzt anlegen
        </Link>
        .
      </p>
    </Reveal>
  );
}
