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

import { type ApprovalRequest } from 'src/types/timeTracking';

import { isResolvingLastVisiblePendingRequest } from '../utils';

type RequestsList = 'pending' | 'processed';

type Props = {
  requests: ApprovalRequest[];
  isFetching: boolean;
  selectedList: RequestsList;
  hasActiveFilters: boolean;
};

export const useResolvedLastPendingState = ({
  requests,
  isFetching,
  selectedList,
  hasActiveFilters,
}: Props) => {
  const [resolvedLastPending, setResolvedLastPending] = useState(false);

  useEffect(() => {
    if (hasActiveFilters) {
      setResolvedLastPending(false);
      return;
    }

    const preserveForEmptyList = requests.length === 0;
    const preserveWhileLastRowRefetches =
      requests.length === 1 && resolvedLastPending && isFetching;
    const skipClear = preserveForEmptyList || preserveWhileLastRowRefetches;

    if (skipClear) return;
    setResolvedLastPending(false);
  }, [requests.length, resolvedLastPending, isFetching, hasActiveFilters]);

  const getWasLastPendingResolution = useCallback(
    (categorizedHourId: string) =>
      isResolvingLastVisiblePendingRequest({
        selectedList,
        hasActiveFilters,
        requests,
        resolvingRequestId: categorizedHourId,
      }),
    [selectedList, hasActiveFilters, requests],
  );

  const markResolved = useCallback((wasLastPending: boolean) => {
    setResolvedLastPending(wasLastPending);
  }, []);

  const showSuccessEmptyState =
    requests.length === 0 &&
    resolvedLastPending &&
    selectedList === 'pending' &&
    !hasActiveFilters;

  return { showSuccessEmptyState, markResolved, getWasLastPendingResolution };
};
