"use client";
import React from "react";
import { UploadButton } from "@/app/components/UploadButton";
import { useToast } from "@/app/components/ui/ToastProvider";

type Props = {
  initialUrl?: string | null;
  onUrlChange?: (url: string | null) => void;
  hideUrlText?: boolean;
};

export function ProfileImageEditor({ initialUrl, onUrlChange, hideUrlText }: Props) {
  const { show } = useToast();
  const [url, setUrl] = React.useState<string>(initialUrl || "");
  const [saving, setSaving] = React.useState(false);

  async function save(newUrl: string | null) {
    try {
      setSaving(true);
      const res = await fetch("/api/me/profile-image", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: newUrl }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "저장 실패");
      show("프로필 이미지가 저장되었습니다");
      setUrl(newUrl || "");
      onUrlChange?.(newUrl);
    } catch (e: any) {
      show(e.message || "저장 실패");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="flex flex-col items-center gap-2">
      <div className="flex gap-2">
        <UploadButton
          onUploaded={(u) => {
            // 정사각 권장
            save(u);
          }}
          aspectRatio={1}
          maxWidth={512}
          maxHeight={512}
          quality={0.9}
        />
        {url ? (
          <button
            type="button"
            onClick={() => save(null)}
            className="px-3 py-2 border border-neutral-300 rounded-md text-sm"
            disabled={saving}
          >
            {saving ? "처리 중..." : "이미지 제거"}
          </button>
        ) : null}
      </div>
      {!hideUrlText && url ? <span className="text-xs text-neutral-500 break-all">{url}</span> : null}
    </div>
  );
}


