// pages/index.tsx
import { renderPostContent } from '@/components/WPRenderer/WPRenderer';
import { buildNestedMenu } from '@/lib/menu';
import axios from 'axios';
import { GetStaticProps } from 'next';
import { useRouter } from 'next/router';
import { ReactElement, useEffect } from 'react';

interface PostData {
  ID: string;
  post_author: string;
  post_date: string;
  post_date_gmt: string;
  post_content: string;
}

interface HomePageProps {
  posts: PostData[];
  lastUpdated: string;
}

export default function HomePage({ posts, lastUpdated }: HomePageProps) {
  const router = useRouter();

  if (router.isFallback) {
    return (
      <div>Loading...</div>
    )
  }

  const { page_id } = router.query

  useEffect(() => {
    if (page_id) {
      axios.get(`/api/pages/id/${page_id}`).then(res => router.push(res.data[0].post_name))
    }
  }, [page_id])

  return (
    <div>
      {posts.map((post) => (
        <div key={post.ID} className="post">
          <div className="post-content">
            {renderPostContent(post.post_content)}
          </div>
        </div>
      ))}
    </div>
  );
}

// ISR Implementation
export const getStaticProps: GetStaticProps = async () => {
  try {
    // Fetch data from your API route
    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'}/api/home`);

    if (!res.ok) {
      throw new Error('Failed to fetch data from API');
    }

    const posts = await res.json();

    return {
      props: {
        posts,
        lastUpdated: new Date().toISOString(),
      },
      // Revalidate every 60 seconds (ISR)
      revalidate: 10,
    };
  } catch (error) {
    console.error('Error fetching data:', error);

    // Return empty props or fallback data
    return {
      props: {
        posts: [],
        lastUpdated: new Date().toISOString(),
      },
      revalidate: 10, // Still try to revalidate even if there's an error
    };
  }
};