"use client";

import { useActionState, useEffect, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { updateProfileAction, deleteAvatarAction } from "@/lib/actions/profile";
import { Field, RequiredMark, SubmitButton } from "@/components/auth/RegisterForm";

export function ProfileForm({
  locale,
  client,
}: {
  locale: string;
  client: {
    id: string;
    firstName: string;
    lastName: string;
    salutation: string;
    pronouns: string;
    nickname: string;
    avatarPath: string;
    birthDate: string;
    phone: string;
    billingStreet: string;
    billingPostCode: string;
    billingCity: string;
    billingCountryCode: string;
    departmentName: string;
    positionName: string;
    role: "client" | "staff";
  };
}) {
  const t = useTranslations("auth");
  const router = useRouter();
  const [state, formAction, pending] = useActionState(updateProfileAction, {});
  const [deletingAvatar, startDeleteAvatar] = useTransition();
  const [salutation, setSalutation] = useState(client.salutation);

  // Siehe gleichnamiger Kommentar in ClientAccountPanel.tsx - revalidatePath
  // in der Server Action reicht allein nicht immer, der Client-Router kann
  // kurz noch die alte Seite zeigen (Fund vom Nutzer, 22.09.2026).
  useEffect(() => {
    if (state.success) router.refresh();
  }, [state, router]);

  return (
    <form action={formAction} className="flex flex-col gap-4" encType="multipart/form-data">
      <input type="hidden" name="locale" value={locale} />

      <div className="flex flex-col items-center gap-3 mb-2">
        <div className="w-20 h-20 rounded-full overflow-hidden border border-white/15 bg-white/5 flex items-center justify-center">
          {client.avatarPath ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={`/api/avatars/${client.id}/${client.avatarPath}`}
              alt=""
              className="w-full h-full object-cover"
            />
          ) : (
            <span className="text-xl text-[var(--rk-ink-muted)]">{client.firstName?.[0]?.toUpperCase() ?? "?"}</span>
          )}
        </div>
        <div className="flex items-center gap-3">
          <label className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] cursor-pointer hover:text-[var(--rk-ink)] transition-colors">
            {t("changeAvatar")}
            <input type="file" name="avatar" accept="image/jpeg,image/png,image/webp" className="hidden" />
          </label>
          {client.avatarPath && (
            <button
              type="button"
              disabled={deletingAvatar}
              onClick={() => startDeleteAvatar(() => deleteAvatarAction())}
              className="text-xs uppercase tracking-[0.1em] text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
            >
              {t("removeAvatar")}
            </button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <Field label={t("firstNameLabel")} name="firstName" type="text" defaultValue={client.firstName} required />
        <Field label={t("lastNameLabel")} name="lastName" type="text" defaultValue={client.lastName} required />
      </div>
      <Field label={t("nicknameLabel")} name="nickname" type="text" defaultValue={client.nickname} />
      {client.role === "client" && (
        <>
          <label className="flex flex-col gap-1.5 text-sm">
            <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
              {t("salutationLabel")}
              <RequiredMark />
            </span>
            <select
              name="salutation"
              required
              value={salutation}
              onChange={(e) => setSalutation(e.target.value)}
              className="bg-transparent border border-white/15 rounded-lg px-3.5 py-2.5 text-[var(--rk-ink)] focus:outline-none focus:border-white/50 transition-colors"
            >
              <option value="" disabled>
                {t("salutationSelectPlaceholder")}
              </option>
              <option value="herr">{t("salutationHerr")}</option>
              <option value="frau">{t("salutationFrau")}</option>
              <option value="divers">{t("salutationDivers")}</option>
            </select>
          </label>
          {salutation === "divers" && (
            <Field label={t("pronounsLabel")} name="pronouns" type="text" defaultValue={client.pronouns} autoComplete="off" />
          )}
          <Field
            label={t("birthDateLabel")}
            name="birthDate"
            type="date"
            defaultValue={client.birthDate}
            required
          />
          <Field
            label={t("phoneLabel")}
            name="phone"
            type="tel"
            defaultValue={client.phone}
            required
          />
        </>
      )}

      {client.role === "staff" && (client.departmentName || client.positionName) && (
        <div className="flex flex-col gap-1 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">{t("departmentPositionLabel")}</span>
          <p className="text-[var(--rk-ink)]">{[client.positionName, client.departmentName].filter(Boolean).join(" · ")}</p>
          <p className="text-xs text-[var(--rk-ink-muted)]">{t("departmentPositionHint")}</p>
        </div>
      )}

      <div className="flex flex-col gap-3">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">{t("addressLabel")}</span>
        <Field
          label={t("billingStreetLabel")}
          name="billingStreet"
          type="text"
          defaultValue={client.billingStreet}
          required={client.role === "client"}
        />
        <div className="grid grid-cols-[8rem_1fr] gap-4">
          <Field
            label={t("billingPostCodeLabel")}
            name="billingPostCode"
            type="text"
            defaultValue={client.billingPostCode}
            required={client.role === "client"}
          />
          <Field
            label={t("billingCityLabel")}
            name="billingCity"
            type="text"
            defaultValue={client.billingCity}
            required={client.role === "client"}
          />
        </div>
        <Field
          label={t("billingCountryCodeLabel")}
          name="billingCountryCode"
          type="text"
          defaultValue={client.billingCountryCode || "DE"}
        />
      </div>

      {state.error && <p className="text-sm text-red-400">{state.error}</p>}
      {state.success && <p className="text-sm text-emerald-400">{t("profileSaved")}</p>}
      <SubmitButton pending={pending} label={t("saveProfile")} />
    </form>
  );
}
