/**
 * Hook for fetching and managing Approver Performance data
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import type { DateRange } from '@/services/dashboard.service';
import type { ApproverPerformance } from '@/services/dashboard.service';
import dashboardService from '@/services/dashboard.service';
import type { ApproverPerformanceRequest } from '../types/approverPerformance.types';

interface UseApproverPerformanceDataOptions {
  approverId: string;
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  statusFilter: string;
  priorityFilter: string;
  slaComplianceFilter: string;
  searchTerm: string;
  itemsPerPage: number;
}

export function useApproverPerformanceData({
  approverId,
  dateRange,
  customStartDate,
  customEndDate,
  statusFilter,
  priorityFilter,
  slaComplianceFilter,
  searchTerm,
  itemsPerPage
}: UseApproverPerformanceDataOptions) {
  const [requests, setRequests] = useState<ApproverPerformanceRequest[]>([]);
  const [approverStats, setApproverStats] = useState<ApproverPerformance | null>(null);
  const [allFilteredRequests, setAllFilteredRequests] = useState<ApproverPerformanceRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalRecords, setTotalRecords] = useState(0);

  const isInitialMount = useRef(true);

  // Fetch stats for this approver (ONLY on date/priority/SLA changes)
  const fetchApproverStats = useCallback(async () => {
    if (!approverId) {
      return;
    }
    
    try {
      const dateRangeToSend = dateRange === 'all' ? undefined : dateRange;
      
      const stats = await dashboardService.getSingleApproverStats(
        approverId,
        dateRangeToSend,
        customStartDate,
        customEndDate,
        priorityFilter !== 'all' ? priorityFilter : undefined,
        slaComplianceFilter !== 'all' ? slaComplianceFilter : undefined
      );
      
      setApproverStats(stats);
    } catch (error) {
      console.error('[ApproverPerformance] Failed to fetch approver stats:', error);
      setApproverStats(null);
    }
  }, [approverId, dateRange, customStartDate, customEndDate, priorityFilter, slaComplianceFilter]);

  // Fetch requests for this approver (on ANY filter change)
  const fetchRequests = useCallback(async (page: number = 1) => {
    if (!approverId) {
      setLoading(false);
      return;
    }
    
    try {
      setLoading(true);
      
      // Fetch current page only (server-side pagination)
      const result = await dashboardService.getRequestsByApprover(
        approverId,
        page,
        itemsPerPage,
        dateRange === 'all' ? undefined : dateRange,
        customStartDate,
        customEndDate,
        statusFilter !== 'all' ? statusFilter : undefined,
        priorityFilter !== 'all' ? priorityFilter : undefined,
        slaComplianceFilter !== 'all' ? slaComplianceFilter : undefined,
        searchTerm || undefined
      );
      
      setRequests(result.requests);
      setTotalRecords(result.pagination.totalRecords);
      setTotalPages(result.pagination.totalPages);
      setCurrentPage(result.pagination.currentPage);
      setAllFilteredRequests(result.requests);
    } catch (error) {
      console.error('Failed to fetch requests:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [
    approverId,
    dateRange,
    customStartDate,
    customEndDate,
    statusFilter,
    priorityFilter,
    slaComplianceFilter,
    searchTerm,
    itemsPerPage
  ]);

  // Initial fetch
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      fetchApproverStats(); // Fetch stats once on mount
      fetchRequests(1);      // Fetch requests once on mount
    }
  }, []); // Only run on mount

  // Refetch stats ONLY when date/priority/SLA changes (NOT status or search)
  useEffect(() => {
    if (!isInitialMount.current) {
      fetchApproverStats();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    dateRange,
    customStartDate,
    customEndDate,
    priorityFilter,
    slaComplianceFilter
    // NO statusFilter, NO searchTerm - stats don't depend on these
  ]);

  // Refetch requests when ANY filter changes (including status and search)
  useEffect(() => {
    if (!isInitialMount.current) {
      fetchRequests(1);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    dateRange,
    customStartDate,
    customEndDate,
    statusFilter,
    priorityFilter,
    slaComplianceFilter,
    searchTerm
  ]);

  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    fetchApproverStats(); // Refresh stats
    fetchRequests(1);      // Refresh requests
  }, [fetchApproverStats, fetchRequests]);

  const handlePageChange = useCallback((page: number) => {
    // Use server-side pagination - fetch from backend
    fetchRequests(page);
  }, [fetchRequests]);

  return {
    requests,
    approverStats,
    allFilteredRequests,
    loading,
    refreshing,
    currentPage,
    totalPages,
    totalRecords,
    handleRefresh,
    handlePageChange
  };
}

