import { renderPostContent } from '@/components/WPRenderer/WPRenderer';
import { GetStaticPaths, GetStaticProps } from 'next';
import { useRouter } from 'next/router';

interface Post {
    ID: string;
    post_title: string;
    post_content: string;
    post_name: string;
    post_type: string;
    post_date: string;
    post_modified: string;
    post_excerpt: string | null;
    post_author: string;
}

interface PageProps {
    post: Post | null;
}

export default function PostPage({ post }: PageProps) {
    const router = useRouter();

    if (!post) {
        return <div>Публикация не найдена</div>;
    }

    return (
        <div className="container mx-auto py-8 max-w-5xl">
            <article className="prose lg:prose-xl max-w-none">
                <h1>{post.post_title}</h1>
                <div className="text-gray-600 mb-6">
                    <time>
                        {post.post_date}
                    </time>
                </div>
                {/* Render WordPress content */}
                {renderPostContent(post.post_content)}
            </article>
        </div>
    );
}

export const getStaticPaths: GetStaticPaths = async () => {
    // Fetch all slugs from API
    console.log("getting all slugs")
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/posts/slugs`);
        const posts = await response.json();

        const paths = posts.map((post: { post_name: string }) => ({
            params: { slug: post.post_name },
        }));

        console.log("fetched all slugs")
        return {
            paths: paths,
            fallback: true, // or 'true' if you want to generate on-demand
        };
    } catch (error) {
        console.log("couldn't fetch all slugs")

        return {
            paths: [],
            fallback: true, // or 'true' if you want to generate on-demand
        };
    }
};

export const getStaticProps: GetStaticProps = async (context) => {
    const { slug } = context.params!;
    console.log("fetching post", slug)

    try {
        // Fetch post data from API

        const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/posts/slug/${slug}`);

        if (!response.ok) {
            return {
                notFound: true,
            };
        }

        const post = await response.json();

        return {
            props: {
                post,
            },
            revalidate: 60, // Revalidate every 60 seconds (ISR)
        };
    } catch (error) {
        console.error('Error fetching post:', error);
        return {
            notFound: true,
        };
    }
};