"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Reveal } from "../../../components/Reveal";
import type { CustomerProfile } from "../../../lib/customerAuth";
import type { ShippingCountry } from "../../../lib/payload";

const inputClass =
  "w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors";

function Field({
  label,
  wrapperClassName = "flex-1 min-w-0",
  ...props
}: { label: string; wrapperClassName?: string } & React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <label className={`flex flex-col gap-2 items-start ${wrapperClassName}`}>
      <span className="text-label text-text-muted">{label}</span>
      <input {...props} className={inputClass} />
    </label>
  );
}

export function ProfileForm({
  profile,
  shippingCountries,
}: {
  profile: CustomerProfile;
  /** Same admin-configurable list /checkout's own "Land" <select> reads
   * (Payload's shipping-countries collection) — this form used to hardcode
   * its own Deutschland/Österreich/Schweiz options independently, so a
   * country added/removed there never reached the profile page. */
  shippingCountries: ShippingCountry[];
}) {
  const router = useRouter();
  const [hasDifferentShippingAddress, setHasDifferentShippingAddress] = useState(profile.hasDifferentShippingAddress);
  const [shippingDeliveryMethod, setShippingDeliveryMethod] = useState<"address" | "packstation">(
    profile.shippingDeliveryMethod ?? "address",
  );
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [saving, setSaving] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSuccess(false);

    const form = new FormData(e.currentTarget);
    const body = {
      firstName: String(form.get("firstName") ?? ""),
      lastName: String(form.get("lastName") ?? ""),
      // Always a plain street address — same "Rechnungsadresse is never a
      // Packstation" rule as /checkout's own billing card (an invoice
      // needs a real postal address). Packstation is only ever offered
      // below, in the optional "Lieferadresse" section.
      deliveryMethod: "address" as const,
      street: String(form.get("street") ?? "") || undefined,
      zip: String(form.get("zip") ?? ""),
      city: String(form.get("city") ?? ""),
      country: String(form.get("country") ?? ""),
      companyName: String(form.get("companyName") ?? "") || undefined,
      vatId: String(form.get("vatId") ?? "") || undefined,
      hasDifferentShippingAddress,
      shippingFirstName: hasDifferentShippingAddress ? String(form.get("shippingFirstName") ?? "") : undefined,
      shippingLastName: hasDifferentShippingAddress ? String(form.get("shippingLastName") ?? "") : undefined,
      shippingCompanyName: hasDifferentShippingAddress ? String(form.get("shippingCompanyName") ?? "") || undefined : undefined,
      shippingDeliveryMethod: hasDifferentShippingAddress ? shippingDeliveryMethod : undefined,
      shippingStreet: hasDifferentShippingAddress ? String(form.get("shippingStreet") ?? "") || undefined : undefined,
      shippingPackstationNumber: hasDifferentShippingAddress
        ? String(form.get("shippingPackstationNumber") ?? "") || undefined
        : undefined,
      shippingPostNumber: hasDifferentShippingAddress ? String(form.get("shippingPostNumber") ?? "") || undefined : undefined,
      shippingZip: hasDifferentShippingAddress ? String(form.get("shippingZip") ?? "") : undefined,
      shippingCity: hasDifferentShippingAddress ? String(form.get("shippingCity") ?? "") : undefined,
      shippingCountry: hasDifferentShippingAddress ? String(form.get("shippingCountry") ?? "") : undefined,
      shippingContactEmail: hasDifferentShippingAddress ? String(form.get("shippingContactEmail") ?? "") || undefined : undefined,
      shippingContactPhone: hasDifferentShippingAddress ? String(form.get("shippingContactPhone") ?? "") || undefined : undefined,
    };

    try {
      const res = await fetch("/api/account/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Profil konnte nicht gespeichert werden.");
        setSaving(false);
        return;
      }
      setSuccess(true);
      setSaving(false);
      router.refresh();
    } catch {
      setError("Profil konnte gerade nicht gespeichert werden.");
      setSaving(false);
    }
  }

  return (
    <Reveal className="flex flex-col gap-6 items-start w-full">
      <form onSubmit={handleSubmit} className="flex flex-col gap-4 items-start w-full">
        {/* Explicit heading, matching /checkout's own "1. Rechnungsadresse"
            card title — without it, this section and the "Lieferadresse"
            one further down read as one undifferentiated form instead of
            two distinct addresses. */}
        <p className="font-semibold text-body-sm text-text-primary">Rechnungsadresse</p>
        <div className="flex flex-col sm:flex-row gap-4 w-full">
          <Field label="Vorname" name="firstName" type="text" defaultValue={profile.firstName} required />
          <Field label="Nachname" name="lastName" type="text" defaultValue={profile.lastName} required />
        </div>

        {/* Optional B2B fields — prefills /checkout's own Firma/USt-IdNr.
            fields, same "profile default, order keeps its own snapshot"
            split as the address fields below (see Customers.ts). */}
        <div className="flex flex-col sm:flex-row gap-4 w-full">
          <Field label="Firma (optional)" name="companyName" type="text" defaultValue={profile.companyName ?? ""} />
          <Field
            label="USt-IdNr. (optional)"
            name="vatId"
            type="text"
            defaultValue={profile.vatId ?? ""}
            placeholder="DE123456789"
            pattern="[A-Za-z]{2}[A-Za-z0-9]{2,12}"
            title="EU-Format: 2 Buchstaben Länderpräfix + bis zu 12 alphanumerische Zeichen, z. B. DE123456789."
          />
        </div>

        {/* Always a plain street address, no Lieferart/Packstation toggle —
            matches /checkout's own Rechnungsadresse card exactly (an
            invoice needs a real postal address). Packstation is only ever
            offered below, in the optional "Lieferadresse" section. */}
        <Field
          label="Straße und Hausnummer"
          name="street"
          type="text"
          defaultValue={profile.street ?? ""}
          required
          wrapperClassName="w-full"
        />

        <div className="flex flex-col sm:flex-row gap-4 w-full">
          <Field label="PLZ" name="zip" type="text" defaultValue={profile.zip ?? ""} required />
          <Field label="Ort" name="city" type="text" defaultValue={profile.city ?? ""} required />
        </div>

        <label className="flex flex-col gap-2 items-start w-full sm:w-1/2">
          <span className="text-label text-text-muted">Land</span>
          <select name="country" defaultValue={profile.country ?? "Deutschland"} required className={`${inputClass} bg-bg-base`}>
            {shippingCountries.map((c) => (
              <option key={c.name}>{c.name}</option>
            ))}
          </select>
        </label>

        <div className="h-px bg-border w-full" />

        <label className="flex gap-3 items-start w-full cursor-pointer">
          <input
            type="checkbox"
            checked={hasDifferentShippingAddress}
            onChange={(e) => setHasDifferentShippingAddress(e.target.checked)}
            className="size-5 shrink-0 mt-0.5 rounded-xs border border-border accent-brand"
          />
          <span className="text-body-sm text-text-primary">
            Abweichende Lieferadresse hinterlegen — wird beim Checkout vorgeschlagen, sobald dort "Abweichende Lieferadresse" aktiviert wird
          </span>
        </label>

        {hasDifferentShippingAddress && (
          <div className="flex flex-col gap-4 items-start w-full">
            <p className="font-semibold text-body-sm text-text-primary">Lieferadresse</p>
            <div className="flex flex-col sm:flex-row gap-4 w-full">
              <Field label="Vorname" name="shippingFirstName" type="text" defaultValue={profile.shippingFirstName ?? ""} required />
              <Field label="Nachname" name="shippingLastName" type="text" defaultValue={profile.shippingLastName ?? ""} required />
            </div>
            <Field
              label="Firma (optional)"
              name="shippingCompanyName"
              type="text"
              defaultValue={profile.shippingCompanyName ?? ""}
              wrapperClassName="w-full"
            />

            <div className="w-full flex flex-col gap-2 items-start">
              <span className="text-label text-text-muted">Lieferart</span>
              <div className="flex w-full max-w-sm rounded-sm border border-border overflow-hidden">
                <button
                  type="button"
                  onClick={() => setShippingDeliveryMethod("address")}
                  aria-pressed={shippingDeliveryMethod === "address"}
                  className={`flex-1 py-3 text-body-sm font-bold transition-colors ${shippingDeliveryMethod === "address" ? "bg-brand text-text-primary" : "text-text-muted hover:text-text-primary"}`}
                >
                  Lieferadresse
                </button>
                <button
                  type="button"
                  onClick={() => setShippingDeliveryMethod("packstation")}
                  aria-pressed={shippingDeliveryMethod === "packstation"}
                  className={`flex-1 py-3 text-body-sm font-bold border-l border-border transition-colors ${shippingDeliveryMethod === "packstation" ? "bg-brand text-text-primary" : "text-text-muted hover:text-text-primary"}`}
                >
                  Packstation
                </button>
              </div>
            </div>

            {shippingDeliveryMethod === "address" ? (
              <Field
                label="Straße und Hausnummer"
                name="shippingStreet"
                type="text"
                defaultValue={profile.shippingStreet ?? ""}
                required
                wrapperClassName="w-full"
              />
            ) : (
              <div className="flex flex-col sm:flex-row gap-4 w-full">
                <Field
                  label="Packstationnummer"
                  name="shippingPackstationNumber"
                  type="text"
                  defaultValue={profile.shippingPackstationNumber ?? ""}
                  required
                />
                <Field label="Postnummer" name="shippingPostNumber" type="text" defaultValue={profile.shippingPostNumber ?? ""} required />
              </div>
            )}

            <div className="flex flex-col sm:flex-row gap-4 w-full">
              <Field label="PLZ" name="shippingZip" type="text" defaultValue={profile.shippingZip ?? ""} required />
              <Field label="Ort" name="shippingCity" type="text" defaultValue={profile.shippingCity ?? ""} required />
            </div>

            <label className="flex flex-col gap-2 items-start w-full sm:w-1/2">
              <span className="text-label text-text-muted">Land</span>
              <select name="shippingCountry" defaultValue={profile.shippingCountry ?? "Deutschland"} required className={`${inputClass} bg-bg-base`}>
                {shippingCountries.map((c) => (
                  <option key={c.name}>{c.name}</option>
                ))}
              </select>
            </label>

            <div className="flex flex-col sm:flex-row gap-4 w-full">
              <Field
                label="Kontakt-E-Mail (optional)"
                name="shippingContactEmail"
                type="email"
                defaultValue={profile.shippingContactEmail ?? ""}
              />
              <Field
                label="Telefonnummer (optional)"
                name="shippingContactPhone"
                type="tel"
                defaultValue={profile.shippingContactPhone ?? ""}
              />
            </div>
            <p className="text-label text-text-muted">Werden nur dem Versanddienstleister übergeben, z. B. für Lieferbenachrichtigungen.</p>
          </div>
        )}

        {error && <p className="text-label text-red-600">{error}</p>}
        {success && <p className="text-label text-success">Gespeichert.</p>}

        <button
          type="submit"
          disabled={saving}
          className={`px-7 py-3 rounded-sm bg-brand hover:bg-brand-hover font-bold text-body-sm text-text-primary transition-colors ${saving ? "opacity-70 pointer-events-none" : ""}`}
        >
          {saving ? "Speichert…" : "Speichern"}
        </button>
      </form>
    </Reveal>
  );
}
