import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { fetchPost } from "../api";
import { useSiteConfig } from "../ConfigContext";
import { CwdComments } from "../components/CwdComments";
import { MarkdownBody } from "../components/MarkdownBody";
import { formatDateTime } from "../lib/text";

export function PostPage() {
  const { slug = "" } = useParams();
  const { siteTitle } = useSiteConfig();
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [updatedAt, setUpdatedAt] = useState("");
  const [views, setViews] = useState(0);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        setErr(null);
        const post = await fetchPost(decodeURIComponent(slug), true);
        if (cancelled) return;
        setTitle(post.title);
        setContent(post.content || "");
        setUpdatedAt(post.updated_at);
        setViews(Number(post.view_count) || 0);
        document.title = `${post.title} - ${siteTitle}`;
      } catch {
        if (!cancelled) {
          setErr("文章不存在或加载失败");
          document.title = `404 - ${siteTitle}`;
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [slug, siteTitle]);

  if (err) {
    return (
      <>
        <p>
          <Link to="/">返回</Link>
        </p>
        <h1>404</h1>
        <p>{err}</p>
      </>
    );
  }

  return (
    <>
      <p>
        <Link to="/">返回</Link>
      </p>
      <div className="post-with-toc">
        <div className="post-with-toc__main">
          <article>
            <h1>{title}</h1>
            <p className="post-detail-meta">
              <span className="post-detail-time">{formatDateTime(updatedAt)}</span>
              <span className="post-detail-views">浏览 {views}</span>
            </p>
            <MarkdownBody markdown={content} />
          </article>
        </div>
        <aside
          className="post-toc"
          id="post-toc"
          aria-label="文章目录"
          hidden
        >
          <div className="post-toc__inner">
            <p className="post-toc__title">目录</p>
            <nav className="post-toc__nav" id="post-toc-nav" />
          </div>
        </aside>
      </div>
      <CwdComments key={slug} postSlug={decodeURIComponent(slug)} />
    </>
  );
}
