"use client";
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useToast } from "@/app/components/ui/ToastProvider";
import { UploadButton } from "@/app/components/UploadButton";
import { Editor } from "@/app/components/Editor";
import { HeroBanner } from "@/app/components/HeroBanner";

export default function EditPostPage() {
  const params = useParams<{ id: string }>();
  const id = params?.id as string; // slug 값
  const router = useRouter();
  const { show } = useToast();
  const [form, setForm] = useState<{ title: string; content: string } | null>(null);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    (async () => {
      const r = await fetch(`/api/posts/${id}`);
      if (!r.ok) return;
      const { post } = await r.json();
      setForm({ title: post.title, content: post.content });
    })();
  }, [id]);
  async function submit() {
    if (!form) return;
    try {
      setLoading(true);
      const r = await fetch(`/api/posts/${id}`, {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(JSON.stringify(data));
      show("수정되었습니다");
      router.push(`/posts/${id}`);
    } catch (e) {
      show("수정 실패");
    } finally {
      setLoading(false);
    }
  }
  if (!form) return <div className="text-sm text-neutral-600">불러오는 중...</div>;
  return (
    <div className="space-y-6">
      {/* 상단 배너 */}
      <section>
        <HeroBanner />
      </section>

      {/* 수정 카드 */}
      <section className="rounded-xl overflow-hidden bg-white">
        <header className="px-4 py-3 border-b border-neutral-200">
          <h1 className="text-xl md:text-2xl font-bold text-neutral-900">글 수정</h1>
        </header>
        <div className="p-4 md:p-6 space-y-3">
          <input
            className="h-10 w-full rounded-md border border-neutral-300 px-3 text-sm focus:outline-none focus:ring-2 focus:ring-neutral-400"
            placeholder="제목"
            value={form.title}
            onChange={(e) => setForm({ ...form, title: e.target.value })}
          />
          <Editor value={form.content} onChange={(v) => setForm({ ...form, content: v })} placeholder="내용을 입력하세요" />
          <div className="pt-1">
            <UploadButton onUploaded={(url) => setForm((f) => (!f ? f : { ...f, content: `${f.content}\n![image](${url})` }))} />
          </div>
        </div>
        <footer className="px-4 py-3 border-t border-neutral-200 flex items-center justify-end gap-2">
          <button
            type="button"
            className="h-9 px-4 rounded-md border border-neutral-300 bg-white text-sm hover:bg-neutral-100"
            onClick={() => router.back()}
          >
            취소
          </button>
          <button
            disabled={loading}
            onClick={submit}
            className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm hover:bg-neutral-800 disabled:opacity-60"
          >
            {loading ? "저장 중..." : "저장"}
          </button>
        </footer>
      </section>
    </div>
  );
}


