import { useState, useEffect, useCallback } from 'react';
import type { PaginatedResponse, FinanceQueryParams } from '@rent/shared-types';

interface UseTableDataOptions<T> {
  fetchFn: (params: FinanceQueryParams) => Promise<PaginatedResponse<T>>;
  initialParams?: FinanceQueryParams;
  autoLoad?: boolean;
}

interface UseTableDataReturn<T> {
  data: T[];
  loading: boolean;
  total: number;
  page: number;
  pageSize: number;
  params: FinanceQueryParams;
  setParams: (params: Partial<FinanceQueryParams>) => void;
  setPage: (page: number) => void;
  setPageSize: (pageSize: number) => void;
  refresh: () => void;
  reset: () => void;
}

/**
 * 表格数据管理Hook
 * 统一处理分页、筛选、加载状态等逻辑
 */
export function useTableData<T = any>(
  options: UseTableDataOptions<T>
): UseTableDataReturn<T> {
  const { fetchFn, initialParams = {}, autoLoad = true } = options;

  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [params, setParamsState] = useState<FinanceQueryParams>({
    page: 1,
    pageSize: 10,
    ...initialParams,
  });

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetchFn(params);
      setData(response.list);
      setTotal(response.total);
    } catch (error) {
      console.error('Failed to load data:', error);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    if (autoLoad) {
      loadData();
    }
  }, [loadData, autoLoad]);

  const setParams = useCallback((newParams: Partial<FinanceQueryParams>) => {
    setParamsState((prev) => ({
      ...prev,
      ...newParams,
      page: newParams.page !== undefined ? newParams.page : 1, // 重置到第一页
    }));
  }, []);

  const setPage = useCallback((page: number) => {
    setParamsState((prev) => ({ ...prev, page }));
  }, []);

  const setPageSize = useCallback((pageSize: number) => {
    setParamsState((prev) => ({ ...prev, pageSize, page: 1 }));
  }, []);

  const refresh = useCallback(() => {
    loadData();
  }, [loadData]);

  const reset = useCallback(() => {
    setParamsState({
      page: 1,
      pageSize: 10,
      ...initialParams,
    });
  }, [initialParams]);

  return {
    data,
    loading,
    total,
    page: params.page || 1,
    pageSize: params.pageSize || 10,
    params,
    setParams,
    setPage,
    setPageSize,
    refresh,
    reset,
  };
}
