import { useCallback, useRef, useEffect } from 'react';

// Components
import { ClosedRequestsHeader } from './components/ClosedRequestsHeader';
import { ClosedRequestsFilters as ClosedRequestsFiltersComponent } from './components/ClosedRequestsFilters';
import { ClosedRequestsList } from './components/ClosedRequestsList';
import { ClosedRequestsEmpty } from './components/ClosedRequestsEmpty';
import { ClosedRequestsPagination } from './components/ClosedRequestsPagination';

// Hooks
import { useClosedRequests } from './hooks/useClosedRequests';
import { useClosedRequestsFilters } from './hooks/useClosedRequestsFilters';

// Types
import type { ClosedRequestsProps } from './types/closedRequests.types';

export function ClosedRequests({ onViewRequest }: ClosedRequestsProps) {
  // Data fetching hook
  const closedRequests = useClosedRequests({ itemsPerPage: 10 });

  // Filters hook - use ref to avoid circular dependency
  const fetchRef = useRef(closedRequests.fetchRequests);
  fetchRef.current = closedRequests.fetchRequests;

  const filters = useClosedRequestsFilters();
  const prevFiltersRef = useRef({
    searchTerm: filters.searchTerm,
    statusFilter: filters.statusFilter,
    priorityFilter: filters.priorityFilter,
    sortBy: filters.sortBy,
    sortOrder: filters.sortOrder,
  });
  const hasInitialFetchRun = useRef(false);
  
  // Initial fetch on mount - use stored page from Redux
  useEffect(() => {
    const storedPage = filters.currentPage || 1;
    fetchRef.current(storedPage, {
      search: filters.searchTerm || undefined,
      status: filters.statusFilter !== 'all' ? filters.statusFilter : undefined,
      priority: filters.priorityFilter !== 'all' ? filters.priorityFilter : undefined,
          sortBy: filters.sortBy,
          sortOrder: filters.sortOrder,
        });
    hasInitialFetchRun.current = true;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only on mount
  
  // Track filter changes and refetch
  useEffect(() => {
    if (!hasInitialFetchRun.current) return;
    
    const prev = prevFiltersRef.current;
    const hasChanged = 
      prev.searchTerm !== filters.searchTerm ||
      prev.statusFilter !== filters.statusFilter ||
      prev.priorityFilter !== filters.priorityFilter ||
      prev.sortBy !== filters.sortBy ||
      prev.sortOrder !== filters.sortOrder;
    
    if (!hasChanged) return; // No actual change, skip
    
    // Debounce search
    const timeoutId = setTimeout(() => {
      filters.setCurrentPage(1); // Reset to page 1 when filters change
      fetchRef.current(1, {
        search: filters.searchTerm || undefined,
        status: filters.statusFilter !== 'all' ? filters.statusFilter : undefined,
        priority: filters.priorityFilter !== 'all' ? filters.priorityFilter : undefined,
        sortBy: filters.sortBy,
        sortOrder: filters.sortOrder,
  });
      
      // Update previous values
      prevFiltersRef.current = {
        searchTerm: filters.searchTerm,
        statusFilter: filters.statusFilter,
        priorityFilter: filters.priorityFilter,
        sortBy: filters.sortBy,
        sortOrder: filters.sortOrder,
      };
    }, filters.searchTerm !== prev.searchTerm ? 500 : 0);
    
    return () => clearTimeout(timeoutId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters.searchTerm, filters.statusFilter, filters.priorityFilter, filters.sortBy, filters.sortOrder]);

  // Page change handler
  const handlePageChange = useCallback(
    (newPage: number) => {
      if (newPage >= 1 && newPage <= closedRequests.pagination.totalPages) {
        filters.setCurrentPage(newPage); // Update page in Redux
        closedRequests.fetchRequests(newPage, {
          search: filters.searchTerm || undefined,
          status: filters.statusFilter !== 'all' ? filters.statusFilter : undefined,
          priority: filters.priorityFilter !== 'all' ? filters.priorityFilter : undefined,
          sortBy: filters.sortBy,
          sortOrder: filters.sortOrder,
        });
      }
    },
    [closedRequests, filters]
  );

  // Refresh handler
  const handleRefresh = useCallback(() => {
    closedRequests.handleRefresh({
      search: filters.searchTerm || undefined,
      status: filters.statusFilter !== 'all' ? filters.statusFilter : undefined,
      priority: filters.priorityFilter !== 'all' ? filters.priorityFilter : undefined,
      sortBy: filters.sortBy,
      sortOrder: filters.sortOrder,
    });
  }, [closedRequests, filters]);

  return (
    <div className="space-y-4 sm:space-y-6 max-w-7xl mx-auto" data-testid="closed-requests-page">
      {/* Header */}
      <ClosedRequestsHeader
        totalRecords={closedRequests.pagination.totalRecords}
        loading={closedRequests.loading}
        refreshing={closedRequests.refreshing}
        onRefresh={handleRefresh}
      />

      {/* Filters */}
      <ClosedRequestsFiltersComponent
        searchTerm={filters.searchTerm}
        priorityFilter={filters.priorityFilter}
        statusFilter={filters.statusFilter}
        sortBy={filters.sortBy}
        sortOrder={filters.sortOrder}
        activeFiltersCount={filters.activeFiltersCount}
        onSearchChange={filters.setSearchTerm}
        onPriorityChange={filters.setPriorityFilter}
        onStatusChange={filters.setStatusFilter}
        onSortByChange={filters.setSortBy}
        onSortOrderChange={() => filters.setSortOrder(filters.sortOrder === 'asc' ? 'desc' : 'asc')}
        onClearFilters={filters.clearFilters}
      />

      {/* Requests List */}
      <ClosedRequestsList
        requests={closedRequests.requests}
        loading={closedRequests.loading}
        onViewRequest={onViewRequest}
      />

      {/* Empty State */}
      {closedRequests.requests.length === 0 && !closedRequests.loading && (
        <ClosedRequestsEmpty
          searchTerm={filters.searchTerm}
          activeFiltersCount={filters.activeFiltersCount}
          onClearFilters={filters.clearFilters}
        />
      )}

      {/* Pagination */}
      {!closedRequests.loading && (
        <ClosedRequestsPagination
          pagination={closedRequests.pagination}
          onPageChange={handlePageChange}
        />
      )}
    </div>
  );
}

