// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";

import { useRef, useState } from "react";

export default function AvatarEditor({ hasAvatar }: { hasAvatar: boolean }) {
  const fileRef = useRef<HTMLInputElement | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function upload(f: File | undefined) {
    if (!f) return;
    setBusy(true);
    setError(null);
    const fd = new FormData();
    fd.append("photo", f);
    const res = await fetch("/api/profile/avatar", { method: "POST", body: fd });
    const data = await res.json().catch(() => ({}));
    if (res.ok) {
      window.location.reload();
    } else {
      setError(data.error ?? "Téléversement impossible — réessayez.");
      setBusy(false);
    }
  }

  async function remove() {
    setBusy(true);
    setError(null);
    await fetch("/api/profile/avatar", { method: "DELETE" });
    window.location.reload();
  }

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-wrap gap-3">
        <button
          type="button"
          className="btn btn-ghost"
          disabled={busy}
          onClick={() => fileRef.current?.click()}
        >
          {busy ? "Téléversement…" : hasAvatar ? "Changer la photo" : "Ajouter une photo"}
        </button>
        {hasAvatar && (
          <button
            type="button"
            className="btn btn-ghost"
            disabled={busy}
            onClick={remove}
          >
            Retirer la photo
          </button>
        )}
      </div>
      <p className="gk-mono text-[10.5px] text-ink-3">
        JPG, PNG ou WebP (8 Mo max) — recadrée en carré 512 px. Visible sur
        votre carte, votre carte Wallet et toutes les plateformes ·Ka.
      </p>
      {error && (
        <p className="rounded-md border-[1.5px] border-[#b3423a] bg-[#fbe9e7] px-3 py-2 text-[12.5px] font-medium text-[#7c2f2a]">
          {error}
        </p>
      )}
      <input
        ref={fileRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        hidden
        onChange={(e) => upload(e.target.files?.[0] ?? undefined)}
      />
    </div>
  );
}
