'use client';

import { useState } from 'react';
import Pagination from '@/components/layout/pagination';
import { getPosts } from '@/services/blog';
import { IPostThumbResponseData } from '@/app/api/blog/data';
import { IPagination } from '@/models/response';
import { useParams } from 'next/navigation';
import { TLocales } from '@/models/layout';
import { useTranslations } from 'next-intl';
import PostsGridView from './PostsGridView';

export interface IPostsGridProps {
  initialPosts: IPostThumbResponseData[];
  initialPagination: IPagination;
}

export default function PostsGrid({
  initialPosts,
  initialPagination,
}: IPostsGridProps) {
  const t = useTranslations();
  const { locale } = useParams();

  const [posts, setPosts] = useState(initialPosts);
  const [pagination, setPagination] = useState(initialPagination);

  const fetchPage = (page: number) => {
    getPosts(page)
      .then((res) => {
        setPosts(res.data);
        setPagination(res.pagination);
        document
          .getElementById('postList')
          ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      })
      .catch((error) => {
        console.error('Failed to fetch posts:', error);
      });
  };

  return (
    <div className="container mx-auto px-4 py-14 md:py-28">
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
        <PostsGridView posts={posts} locale={locale as TLocales} />
      </div>
      <Pagination {...pagination} onPageChange={fetchPage} />
    </div>
  );
}
