'use client';

import { getProjects } from '@/services/projects';
import { IProjectGridViewProps } from './project';
import ProjectsGrid from './ProjectGrid';
import Pagination from '@/components/layout/pagination';
import { useState } from 'react';

export default function ProjectsGridView({
  initialProjects,
  initialPagination,
}: IProjectGridViewProps) {
  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 (
    <>
      {projects?.length ? <ProjectsGrid projects={projects} /> : <></>}
      <Pagination {...pagination} onPageChange={fetchPage} />
    </>
  );
}
