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

import { useState, useCallback } from 'react';
import workflowApi from '@/services/workflowApi';
import { MyRequest, PaginationState } from '../types/myRequests.types';
import { transformRequests } from '../utils/requestTransformers';

interface UseMyRequestsOptions {
  itemsPerPage?: number;
  initialFilters?: {
    search?: string;
    status?: string;
    priority?: string;
    templateType?: string;
  };
}

export function useMyRequests({ itemsPerPage = 10 }: UseMyRequestsOptions = {}) {
  const [requests, setRequests] = useState<MyRequest[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasFetchedFromApi, setHasFetchedFromApi] = useState(false);
  const [pagination, setPagination] = useState<PaginationState>({
    currentPage: 1,
    totalPages: 1,
    totalRecords: 0,
    itemsPerPage,
  });

  const fetchMyRequests = useCallback(
    async (page: number = 1, filters?: { search?: string; status?: string; priority?: string; templateType?: string }) => {
      try {
        if (page === 1) {
          setLoading(true);
          setRequests([]);
        }

        const result = await workflowApi.listMyInitiatedWorkflows({
          page,
          limit: itemsPerPage,
          search: filters?.search,
          status: filters?.status,
          priority: filters?.priority,
          templateType: filters?.templateType,
        });

        // Extract data - workflowApi now returns { data: [], pagination: {} }
        const items = Array.isArray((result as any)?.data) ? (result as any).data : [];

        const transformedRequests = transformRequests(items);
        setRequests(transformedRequests);
        setHasFetchedFromApi(true);

        // Set pagination data
        const paginationData = (result as any)?.pagination;
        if (paginationData) {
          setPagination({
            currentPage: paginationData.page || 1,
            totalPages: paginationData.totalPages || 1,
            totalRecords: paginationData.total || 0,
            itemsPerPage,
          });
        }
      } catch (error) {
        console.error('[MyRequests] Error fetching requests:', error);
        setRequests([]);
        setHasFetchedFromApi(true);
      } finally {
        setLoading(false);
      }
    },
    [itemsPerPage]
  );

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

  return {
    requests,
    loading,
    hasFetchedFromApi,
    pagination,
    fetchMyRequests,
  };
}

