import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { fetchPosts, type Post } from "../api";
import { useSiteConfig } from "../ConfigContext";
import { formatDateTime, stripMarkdown } from "../lib/text";

export function Home() {
  const { siteTitle } = useSiteConfig();
  const [inputQ, setInputQ] = useState("");
  const [q, setQ] = useState("");
  const [posts, setPosts] = useState<Post[]>([]);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    document.title = siteTitle;
  }, [siteTitle]);

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

  useEffect(() => {
    let cancelled = false;
    (async () => {
     try {
        setErr(null);
        const list = await fetchPosts(q || undefined);
        if (!cancelled) setPosts(list);
      } catch {
        if (!cancelled) setErr("加载失败");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [q]);

  return (
    <>
      <form
        className="home-search"
        onSubmit={(e) => e.preventDefault()}
        style={{ marginBottom: 16 }}
      >
        <label>
          搜索{" "}
          <input
            name="q"
            value={inputQ}
            onChange={(e) => setInputQ(e.target.value)}
            placeholder="标题 / 正文"
          />
        </label>
      </form>
      {q ? (
        <p>
          搜索：<strong>{q}</strong>
        </p>
      ) : null}
      {err ? <p>{err}</p> : null}
      {posts.length ? (
        posts.map((post) => {
          const excerpt =
            post.excerpt || stripMarkdown(post.content).slice(0, 180);
          const views = Number(post.view_count) || 0;
          return (
            <article key={post.id} className="post-card">
              <h2>
                <Link to={`/post/${encodeURIComponent(post.slug)}`}>
                  {post.title}
                </Link>
              </h2>
              <p className="post-excerpt">
                {excerpt}
                {excerpt.length >= 180 ? "…" : ""}
              </p>
              <p className="post-meta">
                <span className="post-card-time">
                  创建于：{formatDateTime(post.created_at)}
                </span>
                <span className="post-card-time">
                  最后更新于：{formatDateTime(post.updated_at)}
                </span>
                <span className="post-card-views">浏览 {views}</span>
              </p>
            </article>
          );
        })
      ) : (
        <p>暂无文章。</p>
      )}
    </>
  );
}
