import { useState, useCallback } from 'react';
import type { Page } from '@/types/base/page';

interface UsePageDataProps<T, P = any> {
  service: (params: P) => Promise<Page<T>>;
  defaultParams?: Partial<P>;
}

interface PageState<T> {
  list: T[];
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  loading: boolean;
}

export function usePageData<T, P = any>({ service, defaultParams }: UsePageDataProps<T, P>) {
  const [state, setState] = useState<PageState<T>>({
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    loading: false
  });

  const loadData = useCallback(async (params?: Partial<P>) => {
    setState(prev => ({ ...prev, loading: true }));
    try {
      const pageData = await service({
        ...defaultParams,
        ...params,
        pageNum: state.pagination.current,
        pageSize: state.pagination.pageSize
      } as P);

      setState(prev => ({
        list: pageData?.content || [],
        pagination: {
          current: prev.pagination.current,
          pageSize: prev.pagination.pageSize,
          total: pageData?.totalElements || 0
        },
        loading: false
      }));
    } catch (error) {
      setState(prev => ({ ...prev, loading: false }));
      throw error;
    }
  }, [service, defaultParams, state.pagination]);

  const onPageChange = useCallback((page: number, pageSize?: number) => {
    setState(prev => ({
      ...prev,
      pagination: {
        ...prev.pagination,
        current: page,
        pageSize: pageSize || prev.pagination.pageSize
      }
    }));
  }, []);

  return {
    ...state,
    loadData,
    onPageChange
  };
} 