/**
 * Hook for fetching and managing Request Lifecycle Report data
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import { dashboardService, type DateRange } from '@/services/dashboard.service';
import { LifecycleRequest, PaginationState } from '../types/detailedReports.types';
import { formatTAT, formatDate } from '../utils/formatting';

const LIFECYCLE_RECORDS_PER_PAGE = 10;

interface UseLifecycleReportOptions {
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
}

export function useLifecycleReport({ dateRange, customStartDate, customEndDate }: UseLifecycleReportOptions) {
  const [lifecycleRequests, setLifecycleRequests] = useState<LifecycleRequest[]>([]);
  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);

        const result = await dashboardService.getLifecycleReport(
          page,
          LIFECYCLE_RECORDS_PER_PAGE,
          dateRange,
          customStartDate,
          customEndDate
        );

        const mapped = result.lifecycleData.map((req: any) => {
          const overallTAT = formatTAT(req.overallTATHours);

          return {
            id: req.requestNumber,
            requestId: req.requestId,
            title: req.title,
            priority: req.priority || 'medium',
            status: req.status,
            initiator: req.initiatorName || 'Unknown',
            initDate: formatDate(req.submissionDate),
            currentStage: req.currentStageName || `Level ${req.currentLevel}`,
            overallTAT,
            currentLevel: req.currentLevel,
            totalLevels: req.totalLevels,
            breachCount: req.breachCount || 0,
          };
        });

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

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

  return {
    lifecycleRequests,
    loading,
    loadingPage,
    error,
    pagination,
    fetchData,
  };
}

