// components/account/AvatarUploader.tsx
"use client";

import { useMemo, useState } from "react";

export default function AvatarUploader({
    avatarId,
    onUpdated,
}: {
    avatarId?: string | null;
    onUpdated?: () => void;
}) {
    const [file, setFile] = useState<File | null>(null);
    const [busy, setBusy] = useState(false);
    const [msg, setMsg] = useState<string | null>(null);

    const API_BASE = useMemo(
        () => (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, ""),
                             []
    );
    const currentUrl = avatarId ? `${API_BASE}/assets/${avatarId}` : null;

    const onUpload = async () => {
        setMsg(null);
        if (!file) {
            setMsg("Choose a file first.");
            return;
        }
        setBusy(true);
        try {
            const fd = new FormData();
            fd.set("file", file, file.name);

            const r = await fetch("/api/account/avatar", { method: "POST", body: fd });
            if (r.status === 401) {
                location.assign(`/auth/sign-in?reauth=1&next=${encodeURIComponent("/portal/account")}`);
                return;
            }
            const j = await r.json().catch(() => ({}));
            if (!r.ok) {
                setMsg(j?.error || "Upload failed");
                return;
            }
            setMsg("Avatar updated.");
            setFile(null);
            onUpdated?.();
        } catch (e: any) {
            setMsg(e?.message || "Upload failed");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="rounded-md border p-4 space-y-3">
        <h3 className="font-semibold">Avatar</h3>

        <div className="flex items-center gap-4">
        <div className="h-16 w-16 rounded-full overflow-hidden border bg-muted flex items-center justify-center">
        {currentUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={currentUrl} alt="Avatar" className="h-full w-full object-cover" />
        ) : (
            <span className="text-xs opacity-60">No Avatar</span>
        )}
        </div>

        <input
        className="text-sm"
        type="file"
        accept="image/*"
        onChange={(e) => setFile(e.currentTarget.files?.[0] ?? null)}
        />
        <button
        onClick={onUpload}
        disabled={busy || !file}
        className="rounded-md bg-black text-white px-3 py-2 text-sm disabled:opacity-60"
        >
        {busy ? "Uploading…" : "Upload"}
        </button>
        </div>

        {msg && <div className="text-sm opacity-80">{msg}</div>}
        </div>
    );
}
