/**
 * Hook for fetching and managing Closed Requests data
 */

import { useState, useCallback } from 'react';
import workflowApi from '@/services/workflowApi';
import { ClosedRequest, PaginationState } from '../types/closedRequests.types';
import { transformClosedRequests } from '../utils/requestTransformers';

interface UseClosedRequestsOptions {
  itemsPerPage?: number;
  initialFilters?: {
    search?: string;
    status?: string;
    priority?: string;
    sortBy?: string;
    sortOrder?: string;
  };
}

export function useClosedRequests({ itemsPerPage = 10 }: UseClosedRequestsOptions = {}) {
  const [requests, setRequests] = useState<ClosedRequest[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [pagination, setPagination] = useState<PaginationState>({
    currentPage: 1,
    totalPages: 1,
    totalRecords: 0,
    itemsPerPage,
  });

  const fetchRequests = useCallback(
    async (page: number = 1, filters?: { search?: string; status?: string; priority?: string; templateType?: string; financialYear?: string; quarter?: string; sortBy?: string; sortOrder?: string }) => {
      try {
        if (page === 1) {
          setLoading(true);
          setRequests([]);
        }
        
        const result = await workflowApi.listClosedByMe({ 
          page, 
          limit: itemsPerPage,
          search: filters?.search,
          status: filters?.status && filters.status !== 'all' ? filters.status : undefined,
          priority: filters?.priority,
          templateType: filters?.templateType,
          financialYear: filters?.financialYear,
          quarter: filters?.quarter,
          sortBy: filters?.sortBy,
          sortOrder: filters?.sortOrder
        });
        
        // Extract data - workflowApi now returns { data: [], pagination: {} }
        const data = Array.isArray((result as any)?.data) 
          ? (result as any).data 
          : [];
        
        const mapped = transformClosedRequests(data);
        setRequests(mapped); // No client-side filtering - backend returns only CLOSED requests
        
        // Set pagination data from backend
        const paginationData = (result as any)?.pagination;
        if (paginationData) {
          // If we filtered out some requests on this page, we need to adjust pagination
          // For simplicity, we'll keep backend's total but note it may be slightly off
          // A better solution would be to filter on backend, but for now this works
          setPagination({
            currentPage: paginationData.page || 1,
            totalPages: paginationData.totalPages || 1,
            totalRecords: paginationData.total || 0,
            itemsPerPage,
          });
        }
      } catch (error) {
        console.error('[ClosedRequests] Error fetching requests:', error);
        setRequests([]);
      } finally {
        setLoading(false);
        setRefreshing(false);
      }
    },
    [itemsPerPage]
  );

  // Initial fetch removed - component handles initial fetch using Redux stored page
  // This prevents duplicate fetches and allows page persistence

  const handleRefresh = useCallback((filters?: { search?: string; status?: string; priority?: string; templateType?: string; financialYear?: string; quarter?: string; sortBy?: string; sortOrder?: string }) => {
    setRefreshing(true);
    fetchRequests(pagination.currentPage, filters);
  }, [fetchRequests, pagination.currentPage]);

  return {
    requests,
    loading,
    refreshing,
    pagination,
    fetchRequests,
    handleRefresh,
  };
}

