'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import ListPageTemplate from '@/components/common/ListPageTemplate';
import Pagination1 from '@/components/common/Pagination1';
import axios from 'axios';

const LoadingSpinner = () => (
  <div className="flex justify-center items-center p-8">
    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
  </div>
);

export default function DynamicListPage({ initialItems, slugArr, basePath, columns, pageSize, totalItems }) {
  const [items, setItems] = useState(initialItems);
  const [total, setTotal] = useState(totalItems);
  const [isLoading, setIsLoading] = useState(false);
  const searchParams = useSearchParams();
  const page = searchParams.get('page');
  const currentPage = Number(page) || 1;

  useEffect(() => {
    const fetchPageData = async () => {
      if (currentPage === 1) {
        setItems(initialItems);
        setTotal(totalItems);
        return;
      }
      setIsLoading(true);
      try {
        const res = await axios.post('/api/get-page-data', {
          slug_list: slugArr,
          page: currentPage,
          page_size: pageSize,
        });
        setItems(res.data.data);
        setTotal(res.data.total);
      } catch (error) {
        console.error('Failed to fetch page data:', error);
        // Optionally, handle the error in the UI
      } finally {
        setIsLoading(false);
      }
    };

    fetchPageData();
  }, [currentPage, slugArr, pageSize, initialItems, totalItems]);

  const listItems = items.map(item => ({
    ...item,
    slug: item.slug,
    title: item.title,
    image: item.image || item.cover || item.img || '',
    additional_title: item.additional_title || '',
    subtitle: item.subtitle || item.content || '',
  }));

  const totalPages = Math.ceil((total || 0) / pageSize);

  return (
    <>
      {isLoading ? (
        <LoadingSpinner />
      ) : (
        <ListPageTemplate items={listItems} basePath={basePath} columns={columns} />
      )}
      <div className="mt-8">
        <Pagination1
          currentPage={currentPage}
          totalPages={totalPages}
          basePath={basePath}
        />
      </div>
    </>
  );
} 