'use client';

import { TLocales } from '@/models/layout';
import { useTranslations } from 'next-intl';
import ProjectsGridView from './projectGridView';
import Pagination from '@/components/layout/pagination';
import { IProjectThumbResponseData } from '@/app/api/projects/data';
import { IPagination } from '@/models/response';
import { useParams } from 'next/navigation';
import { useState } from 'react';
import { getProjects } from '@/services/projects';
export interface IProjectsGridProps {
  initialProjects: IProjectThumbResponseData[];
  initialPagination: IPagination;
}
export default function ProjectsGrid({
  initialProjects,
  initialPagination,
}: IProjectsGridProps) {
  const t = useTranslations();
  const { locale } = useParams();

  const [projects, setProjects] = useState(initialProjects);
  const [pagination, setPagination] = useState(initialPagination);

  const fetchPage = (page: number) => {
    getProjects(page)
      .then((res) => {
        setProjects(res.data);
        setPagination(res.pagination);

        document
          .getElementById('projectList')
          ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      })
      .catch((error) => {
        console.error('Failed to fetch Projects:', 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">
        <ProjectsGridView projects={projects} locale={locale as TLocales} />
      </div>
      <Pagination {...pagination} onPageChange={fetchPage} />
    </div>
  );
}
