import { FormEvent, useEffect, useState } from "react";
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
import {
  deletePostApi,
  fetchPost,
  fetchPosts,
  savePost,
  type Post
} from "../api";
import { useSiteConfig } from "../ConfigContext";

export function AdminDashboard() {
  const { siteTitle } = useSiteConfig();
  const [q, setQ] = useState("");
  const [inputQ, setInputQ] = useState("");
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    document.title = `后台 - ${siteTitle}`;
  }, [siteTitle]);

  useEffect(() => {
    const id = window.setTimeout(() => setQ(inputQ.trim()), 300);
    return () => clearTimeout(id);
  }, [inputQ]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const list = await fetchPosts(q || undefined, {
          credentials: "include"
        });
        if (!cancelled) setPosts(list);
      } catch {
        if (!cancelled) setPosts([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [q]);

  return (
    <>
      <p>
        <Link to="/">返回</Link>
      </p>
      <h1>后台</h1>
      <p>
        <Link to="/admin/new">新建文章</Link>
      </p>
      <section>
        <h2>文章列表</h2>
        <form
          onSubmit={(e) => e.preventDefault()}
        >
          <p>
            <label>
              查询 <input value={inputQ} onChange={(e) => setInputQ(e.target.value)} />
            </label>
          </p>
        </form>
        {posts.length ? (
          posts.map((post) => (
            <article key={post.id}>
              <h3>{post.title}</h3>
              <p>
                ID: {post.id} | Slug: {post.slug} |{" "}
                {post.published ? "已发布" : "草稿"}
              </p>
              <div>
                <Link to={`/admin/edit/${post.id}`}>编辑</Link>
                <DeleteButton postId={post.id} onDone={() => setPosts((p) => p.filter((x) => x.id !== post.id))} />
              </div>
            </article>
          ))
        ) : (
          <p>没有找到文章。</p>
        )}
      </section>
    </>
  );
}

function DeleteButton({
  postId,
  onDone
}: {
  postId: number;
  onDone: () => void;
}) {
  return (
    <form
      style={{ display: "inline", marginLeft: 8 }}
      onSubmit={async (e) => {
        e.preventDefault();
        if (!confirm("确定删除？")) return;
        try {
          await deletePostApi(postId);
          onDone();
        } catch {
          alert("删除失败");
        }
      }}
    >
      <button type="submit">删除</button>
    </form>
  );
}

export function AdminEditor() {
  const { id: idParam } = useParams();
  const [search] = useSearchParams();
  const navigate = useNavigate();
  const { siteTitle } = useSiteConfig();
  const id = idParam ? Number(idParam) : Number(search.get("id") || "") || null;

  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [excerpt, setExcerpt] = useState("");
  const [content, setContent] = useState("");
  const [published, setPublished] = useState(true);

  useEffect(() => {
    document.title = `后台 - ${siteTitle}`;
  }, [siteTitle]);

  useEffect(() => {
    if (!id) {
      setTitle("");
      setSlug("");
      setExcerpt("");
      setContent("");
      setPublished(true);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const post = await fetchPost(String(id), false, {
          credentials: "include"
        });
        if (cancelled) return;
        setTitle(post.title);
        setSlug(post.slug);
        setExcerpt(post.excerpt || "");
        setContent(post.content || "");
        setPublished(!!post.published);
      } catch {
        if (!cancelled) alert("加载文章失败");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [id]);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    try {
      const payload = {
        title,
        slug,
        excerpt,
        content,
        published: published ? 1 : 0,
        id: id || undefined
      };
      const saved = await savePost(payload, id);
      navigate(`/admin/edit/${saved.id}?saved=1`, { replace: true });
    } catch (er) {
      alert(er instanceof Error ? er.message : "保存失败");
    }
  }

  return (
    <>
      <p>
        <Link to="/admin">返回后台</Link>
      </p>
      <h1>{id ? `编辑 #${id}` : "新建文章"}</h1>
      <form onSubmit={onSubmit}>
        <p>
          <label>
            标题
            <br />
            <input value={title} onChange={(e) => setTitle(e.target.value)} required />
          </label>
        </p>
        <p>
          <label>
            Slug
            <br />
            <input value={slug} onChange={(e) => setSlug(e.target.value)} />
          </label>
        </p>
        <p>
          <label>
            摘要
            <br />
            <input value={excerpt} onChange={(e) => setExcerpt(e.target.value)} />
          </label>
        </p>
        <p>
          <label>
            内容
            <br />
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              required
              rows={18}
              style={{ width: "100%", maxWidth: "100%" }}
            />
          </label>
        </p>
        <p>
          <label>
            <input
              type="checkbox"
              checked={published}
              onChange={(e) => setPublished(e.target.checked)}
            />{" "}
            发布
          </label>
        </p>
        <p>
          <button type="submit">保存</button>
        </p>
      </form>
    </>
  );
}
