"use client";

import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import type { Post, Category, Tag } from "@/lib/store";
import { useToast, safeFetch } from "@/components/Toast";
import PostForm from "@/components/admin/PostForm";
import type { PostFormData } from "@/components/admin/PostForm";

export default function EditPostPage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const { toast } = useToast();

  const [post, setPost] = useState<Post | null>(null);
  const [categories, setCategories] = useState<Category[]>([]);
  const [allTags, setAllTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      safeFetch(`/api/posts/${id}`, undefined, toast).then((r) => r.json()),
      safeFetch("/api/categories", undefined, toast).then((r) => r.json()),
      safeFetch("/api/tags", undefined, toast).then((r) => r.json()),
    ]).then(([p, cats, tgs]) => {
      setPost(p);
      setCategories(cats);
      setAllTags(tgs);
    }).catch(() => {})
      .finally(() => setLoading(false));
  }, [id, toast]);

  async function handleSubmit(data: PostFormData) {
    await safeFetch(`/api/posts/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    }, toast);
    toast("文章已更新", "success");
    router.push("/admin/posts");
  }

  if (loading) return <div className="font-sans text-muted-foreground">加载中...</div>;
  if (!post) return <div className="font-sans text-red-600">文章未找到</div>;

  return (
    <div>
      <div className="flex items-center gap-4 mb-8">
        <button onClick={() => router.back()} className="font-sans text-sm text-muted-foreground hover:text-foreground transition-colors">
          ← 返回
        </button>
        <h1 className="font-display text-3xl font-medium">编辑文章</h1>
      </div>
      <PostForm
        mode="edit"
        initialData={post}
        categories={categories}
        tags={allTags}
        onSubmit={handleSubmit}
        onCancel={() => router.back()}
      />
    </div>
  );
}
