// frontend/src/pages/Blog.tsx
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

interface Post {
  id: number;
  title: string;
  content: string;
  created_at: string;
}

function Blog() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    fetchPosts();
  }, []);

  const fetchPosts = async () => {
    try {
      const response = await fetch("/api/v1/posts");
      if (response.ok) {
        const data = await response.json();
        const fetchedPosts = data.data || [];

        // Сортируем от новых к старым
        const sorted = fetchedPosts.sort((a: Post, b: Post) => {
          const dateA = new Date(a.created_at).getTime();
          const dateB = new Date(b.created_at).getTime();
          return dateB - dateA; // От нового к старому
        });

        setPosts(sorted);
      }
    } catch (error) {
      console.error("Failed to fetch posts:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const truncateContent = (content: string, sentences: number = 3) => {
    const plainText = content
      .replace(/#{1,6}\\s/g, "")
      .replace(/\\*\\*(.+?)\\*\\*/g, "$1")
      .replace(/\\*(.+?)\\*/g, "$1")
      .replace(/`{3}[\\s\\S]*?`{3}/g, "")
      .replace(/`(.+?)`/g, "$1")
      .replace(/\\[(.+?)\\]\\(.+?\\)/g, "$1")
      .replace(/!\\[.*?\\]\\(.+?\\)/g, "")
      .replace(/\\n+/g, " ")
      .trim();

    const sentenceRegex = /[^.!?]+[.!?]+/g;
    const matches = plainText.match(sentenceRegex);

    if (!matches || matches.length === 0) {
      if (plainText.length <= 200) return plainText;
      return plainText.substring(0, 200).trim() + "...";
    }

    const truncated = matches.slice(0, sentences).join(" ");
    return truncated + (matches.length > sentences ? "..." : "");
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return "";

    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      console.error("Invalid date from API:", dateString);
      return "recent";
    }

    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-white text-lg font-['Commit_Mono',monospace]">
          Loading...
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-black text-white font-['Commit_Mono',monospace]">
      <div className="max-w-[900px] mx-auto px-4 sm:px-6 py-10 sm:py-16">
        {/* Минимальный заголовок */}
        <div className="mb-10">
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-400 mb-1">
            blog
          </h1>
          <div className="h-px w-24 bg-gray-800" />
        </div>

        {posts.length === 0 ? (
          <div className="py-16">
            <p className="text-gray-500 text-sm">No posts yet.</p>
          </div>
        ) : (
          <div className="space-y-10 sm:space-y-12">
            {posts.map((post, index) => (
              <div key={post.id}>
                <article className="flex flex-col gap-3 text-left">
                  <h2 className="text-xl sm:text-2xl font-semibold text-[hsl(270,73%,63%)]">
                    {post.title}
                  </h2>

                  <div className="text-xs sm:text-sm text-gray-500">
                    {formatDate(post.created_at)}
                  </div>

                  <p className="text-gray-300 text-sm sm:text-base leading-relaxed">
                    {truncateContent(post.content, 3)}
                  </p>

                  <div className="mt-2">
                    <button
                      onClick={() => navigate(`/blog/${post.id}`)}
                      className="inline-flex items-center px-4 py-2 border border-gray-700 rounded hover:border-[hsl(270,73%,63%)] hover:text-[hsl(270,73%,63%)] transition-colors text-xs sm:text-sm"
                    >
                      Read more
                      <span className="ml-2 text-[hsl(270,73%,63%)]">→</span>
                    </button>
                  </div>
                </article>

                {index !== posts.length - 1 && (
                  <div className="mt-6 sm:mt-8">
                    <div className="h-px w-full bg-gradient-to-r from-[hsl(270,73%,63%)] via-gray-800 to-transparent opacity-60" />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default Blog;
