"use client";

import { useEffect, useState } from "react";
import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { updateClientAccountAction } from "@/lib/actions/clientAccounts";

function FieldLabel({ children, required }: { children: React.ReactNode; required?: boolean }) {
  return (
    <span className="text-[var(--rk-ink-muted)]">
      {children}
      {required && (
        <span className="text-[var(--rk-accent)]" title="Pflichtfeld">
          {" "}
          *
        </span>
      )}
    </span>
  );
}

const inputCls = "bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50";

export function ClientAccountPanel({
  clientId,
  role,
  firstName,
  lastName,
  salutation,
  pronouns,
  nickname,
  email,
  phone,
  billingStreet,
  billingPostCode,
  billingCity,
  billingCountryCode,
  company,
}: {
  clientId: string;
  role: "client" | "staff";
  firstName: string;
  lastName: string;
  salutation: string;
  pronouns: string;
  nickname: string;
  email: string;
  phone: string;
  billingStreet: string;
  billingPostCode: string;
  billingCity: string;
  billingCountryCode: string;
  company: string;
}) {
  const router = useRouter();
  const [state, formAction, pending] = useActionState(updateClientAccountAction.bind(null, clientId), {});
  const [salutationValue, setSalutationValue] = useState(salutation);

  // revalidatePath in der Server Action invalidiert nur den Server-seitigen
  // Cache - der Client-Router kann trotzdem kurz noch die alte, vor dem
  // Speichern geladene Seite zeigen (Fund vom Nutzer, 22.09.2026: Änderungen
  // "setzen sich optisch erstmal zum alten zurück", erst ein manueller
  // Reload zeigt den neuen Stand). router.refresh() erzwingt einen echten
  // Refetch der Server Components mit den frisch gespeicherten Daten.
  useEffect(() => {
    if (state.success) router.refresh();
  }, [state, router]);

  return (
    <form
      action={formAction}
      className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 mb-8 flex flex-col gap-3"
    >
      <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Kundenkonto verwalten</p>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1.5 text-sm">
          <FieldLabel required>Vorname</FieldLabel>
          <input name="firstName" defaultValue={firstName} required className={inputCls} />
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <FieldLabel required>Nachname</FieldLabel>
          <input name="lastName" defaultValue={lastName} required className={inputCls} />
        </label>
      </div>

      {role === "client" && (
        <>
          <label className="flex flex-col gap-1.5 text-sm">
            <FieldLabel required>Anrede</FieldLabel>
            <select
              name="salutation"
              required
              value={salutationValue}
              onChange={(e) => setSalutationValue(e.target.value)}
              className={inputCls}
            >
              <option value="" disabled>
                Bitte wählen
              </option>
              <option value="herr">Herr</option>
              <option value="frau">Frau</option>
              <option value="divers">Divers</option>
            </select>
          </label>
          {salutationValue === "divers" && (
            <label className="flex flex-col gap-1.5 text-sm">
              <FieldLabel>Pronomen (optional)</FieldLabel>
              <input name="pronouns" defaultValue={pronouns} className={inputCls} />
            </label>
          )}
        </>
      )}

      <label className="flex flex-col gap-1.5 text-sm">
        <FieldLabel>Nickname (optional)</FieldLabel>
        <input name="nickname" defaultValue={nickname} className={inputCls} />
      </label>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1.5 text-sm">
          <FieldLabel required>E-Mail</FieldLabel>
          <input name="email" type="email" defaultValue={email} required className={inputCls} />
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <FieldLabel>Telefonnummer</FieldLabel>
          <input name="phone" type="tel" defaultValue={phone} className={inputCls} />
        </label>
      </div>

      <div className="flex flex-col gap-3">
        <FieldLabel>Anschrift</FieldLabel>
        <input name="billingStreet" placeholder="Straße & Hausnummer" defaultValue={billingStreet} className={inputCls} />
        <div className="grid grid-cols-[8rem_1fr] gap-3">
          <input name="billingPostCode" placeholder="PLZ" defaultValue={billingPostCode} className={inputCls} />
          <input name="billingCity" placeholder="Ort" defaultValue={billingCity} className={inputCls} />
        </div>
        <input
          name="billingCountryCode"
          placeholder="Land (Ländercode, z. B. DE)"
          defaultValue={billingCountryCode || "DE"}
          className={inputCls}
        />
      </div>

      <label className="flex flex-col gap-1.5 text-sm">
        <FieldLabel>Unternehmen (optional)</FieldLabel>
        <input name="company" defaultValue={company} maxLength={200} className={inputCls} />
      </label>

      <label className="flex flex-col gap-1.5 text-sm">
        <FieldLabel>Neues Passwort setzen (leer lassen, um es nicht zu ändern)</FieldLabel>
        <input name="password" type="password" minLength={8} autoComplete="new-password" className={inputCls} />
      </label>

      <button
        type="submit"
        disabled={pending}
        className="self-start border border-white/30 rounded-lg px-4 py-2 text-xs uppercase tracking-[0.15em] hover:border-white disabled:opacity-50"
      >
        Speichern
      </button>
      {state.error && <p className="text-sm text-red-400">{state.error}</p>}
      {state.success && <p className="text-sm text-emerald-400">Gespeichert.</p>}
    </form>
  );
}
