"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";

const fieldClass =
  "w-full rounded-2xl border border-anouma-taupe/30 bg-white px-5 py-3.5 text-base text-anouma-plum placeholder:text-anouma-plum/50 focus:border-anouma-mauve-dark focus:outline-none";

export function ProfileForm({ id, name, phone }: { id: number; name: string; phone: string }) {
  const router = useRouter();
  const [status, setStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("saving");
    const data = new FormData(e.currentTarget);

    const res = await fetch(`/api/customers/${id}`, {
      method: "PATCH",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: String(data.get("name") ?? ""),
        phone: String(data.get("phone") ?? "") || null,
      }),
    });

    if (res.ok) {
      setStatus("saved");
      router.refresh();
    } else {
      setStatus("error");
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div>
        <label htmlFor="name" className="mb-2 block text-sm font-medium text-anouma-plum">
          Name
        </label>
        <input id="name" name="name" type="text" required defaultValue={name} className={fieldClass} />
      </div>
      <div>
        <label htmlFor="phone" className="mb-2 block text-sm font-medium text-anouma-plum">
          Telefonnummer (optional)
        </label>
        <input id="phone" name="phone" type="tel" defaultValue={phone} className={fieldClass} />
      </div>
      <button
        type="submit"
        disabled={status === "saving"}
        className="rounded-full bg-anouma-mauve-dark px-7 py-3 text-sm font-medium text-white hover:bg-anouma-plum disabled:opacity-60"
      >
        {status === "saving" ? "Wird gespeichert …" : "Speichern"}
      </button>
      {status === "saved" && <p className="text-sm text-anouma-olive">Gespeichert.</p>}
      {status === "error" && <p className="text-sm text-red-700">Speichern fehlgeschlagen.</p>}
    </form>
  );
}
