import { useState, useEffect, useCallback } from 'react';
import type { GridPaginationModel, GridFilterModel } from '@mui/x-data-grid';
import { SchemaService } from '../services/api';

export const useTableData = (
  activeTable: string | null, 
  activeDatabase: string | null,
  paginationModel: GridPaginationModel,
  filterModel?: GridFilterModel
) => {
  const [rows, setRows] = useState<any[]>([]);
  const [rowCount, setRowCount] = useState(0);
  const [loading, setLoading] = useState(false);

  const fetchData = useCallback(async () => {
    if (!activeTable || !activeDatabase) return;

    setLoading(true);
    try {
      const params: any = {
        skip: paginationModel.page * paginationModel.pageSize,
        take: paginationModel.pageSize,
        requireTotalCount: true,
        database: activeDatabase,
      };

      if (filterModel && filterModel.items.length > 0) {
        params.filters = JSON.stringify(filterModel.items);
      }

      const response = await SchemaService.getTableData(activeTable, params);
      
      const dataWithIds = response.data.data.map((row: any, index: number) => ({
        id: row.id || row.ID || `row-${index}-${paginationModel.page}`,
        ...row,
      }));

      setRows(dataWithIds);
      setRowCount(response.data.totalCount || 0);
    } catch (error) {
      console.error('Data loading error', error);
    } finally {
      setLoading(false);
    }
  }, [activeTable, activeDatabase, paginationModel, filterModel]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return { rows, rowCount, loading, refetch: fetchData };
};
