/**
 * Hook for fetching and managing Workflow Aging Report data
 */

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { dashboardService, type DateRange } from '@/services/dashboard.service';
import { AgingWorkflow, PaginationState } from '../types/detailedReports.types';

const RECORDS_PER_PAGE = 20;

interface UseAgingReportOptions {
  threshold: string;
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  searchQuery?: string;
}

export function useAgingReport({
  threshold,
  dateRange,
  customStartDate,
  customEndDate,
  searchQuery = '',
}: UseAgingReportOptions) {
  const [agingWorkflows, setAgingWorkflows] = useState<AgingWorkflow[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingPage, setLoadingPage] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pagination, setPagination] = useState<PaginationState>({
    page: 1,
    totalPages: 1,
    totalRecords: 0,
  });
  const isInitialMount = useRef(true);

  const fetchData = useCallback(
    async (page: number = 1) => {
      const isInitialLoad = page === 1 && isInitialMount.current;

      try {
        if (isInitialLoad) {
          setLoading(true);
        } else {
          setLoadingPage(true);
        }
        setError(null);

        // Validate threshold before fetching
        const thresholdValue = parseInt(threshold, 10);
        if (isNaN(thresholdValue) || thresholdValue < 1) {
          setError('Please enter a valid threshold (minimum 1 day)');
          return;
        }

        const result = await dashboardService.getWorkflowAgingReport(
          thresholdValue,
          page,
          RECORDS_PER_PAGE,
          dateRange,
          customStartDate,
          customEndDate
        );

        const mapped = result.agingData.map((req: any) => {
          return {
            id: req.requestNumber || req.requestId,
            requestId: req.requestId,
            title: req.title,
            initiator: req.initiatorName || 'Unknown',
            startDate: req.submissionDate ? new Date(req.submissionDate).toLocaleDateString() : 'N/A',
            daysOpen: req.daysOpen,
            currentStage: req.currentStageName || `Level ${req.currentLevel}`,
            assignedTo: req.currentApproverName || 'N/A',
            priority: req.priority || 'medium',
            status: req.status || 'pending',
          };
        });

        setAgingWorkflows(mapped);
        setPagination({
          page: result.pagination.currentPage,
          totalPages: result.pagination.totalPages,
          totalRecords: result.pagination.totalRecords,
        });
      } catch (error: any) {
        console.error('Failed to fetch aging data:', error);
        setError(error?.message || 'Failed to load aging data');
      } finally {
        if (isInitialLoad) {
          setLoading(false);
        } else {
          setLoadingPage(false);
        }
      }
      if (isInitialLoad) {
        isInitialMount.current = false;
      }
    },
    [threshold, dateRange, customStartDate, customEndDate]
  );

  // Filter aging workflows based on search (client-side filtering for current page only)
  const filteredAgingWorkflows = useMemo(() => {
    return agingWorkflows.filter((workflow) => {
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return (
        workflow.id?.toLowerCase().includes(query) ||
        workflow.title?.toLowerCase().includes(query) ||
        workflow.initiator?.toLowerCase().includes(query)
      );
    });
  }, [agingWorkflows, searchQuery]);

  // Fetch data when threshold or date range changes
  useEffect(() => {
    if (dateRange === 'custom' && (!customStartDate || !customEndDate)) {
      return;
    }
    fetchData(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [threshold, dateRange, customStartDate, customEndDate]);

  return {
    agingWorkflows: filteredAgingWorkflows,
    loading,
    loadingPage,
    error,
    pagination,
    fetchData,
  };
}

