import { useState, useEffect, useCallback } from 'react';
import apiService from '../services/apiService';

export interface PMScheduleGenerator {
  name: string;
  creation?: string;
  modified?: string;
  modified_by?: string;
  owner?: string;
  docstatus?: number;
  [key: string]: any;
}

export function usePMScheduleGenerators(
  filters: Record<string, any> = {},
  limit: number = 1000,
  offset: number = 0,
  orderBy: string = 'creation desc'
) {
  const [pmSchedules, setPMSchedules] = useState<PMScheduleGenerator[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refetchTrigger, setRefetchTrigger] = useState(0);

  // Stringify filters to prevent object reference changes from causing re-renders
  const filtersJson = JSON.stringify(filters);

  useEffect(() => {
    let isCancelled = false;

    const fetchPMSchedules = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await apiService.getDoctypeRecords(
          'PM Schedule Generator',
          filters,
          ['name', 'creation', 'modified', 'docstatus', 'pm_schedule_name'],
          limit,
          offset
        );

        if (!isCancelled) {
          setPMSchedules(response.records || []);
          setTotalCount(response.total_count || 0);
          setHasMore(response.has_more || false);
        }
      } catch (err) {
        if (!isCancelled) {
          console.error('Error fetching PM Schedule Generators:', err);
          setError(err instanceof Error ? err.message : 'Failed to fetch PM Schedule Generators');
          setPMSchedules([]);
          setTotalCount(0);
        }
      } finally {
        if (!isCancelled) {
          setLoading(false);
        }
      }
    };

    fetchPMSchedules();

    return () => {
      isCancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filtersJson, limit, offset, orderBy, refetchTrigger]);

  const refetch = useCallback(() => {
    setRefetchTrigger(prev => prev + 1);
  }, []);

  return {
    pmSchedules,
    totalCount,
    hasMore,
    loading,
    error,
    refetch
  };
}
