/**
 * @file AutoOpen.tsx - Automatically opens the first unlocked work item from either the user's inbox or a specified queue, based on the saved open mode preference in localStorage.
 * Shows a loading spinner while determining which work item to open, then navigates to the Processing page.
 */

import { getStoredOpenMode } from '../utils/localStorage.ts';
import { useEffect } from 'react';
import { getInboxWorkItems, getQueueWorkItems } from '../api/workItem.ts';
import { useNavigate, useParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext.tsx';
import { Spinner } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';
import type { FetchError } from '../utils/fetchHelper.ts';
import { toast } from 'react-toastify';

/**
 * Auto-open page that automatically opens the first unlocked work item in either the user's inbox or last queue, if their auto-open mode is not "manual".
 */
export const AutoOpen = () => {
  const params = useParams();
  const processId = Number(params.processId);
  const queueId = Number(params.queueId);

  const { username } = useAuth();
  const navigate = useNavigate();

  // Handles the opening of WorkItems once one has been selected
  const openWorkItem = (
    processId: number,
    queueId: number,
    workItemReferenceId: number
  ) => {
    navigate(
      '/processing/' + processId + '/' + queueId + '/' + workItemReferenceId
    );
  };

  // Function retrieves list of WorkItems for the user's inbox and picks the first unlocked one to open
  const retrieveInboxWorkItems = async () => {
    getInboxWorkItems()
      .then((result) => {
        const first = result.find((workItem) =>
          [null, username].includes(workItem.lockedBy)
        );

        if (first) {
          openWorkItem(
            first.processId as number,
            first.queueId as number,
            first.workItemReferenceId
          );
        } else {
          navigate('/');
        }
      })
      .catch((error: FetchError) => {
        toast.error(error.message);
        navigate('/');
      });
  };

  // Function retrieves list of WorkItems for queue in params and picks the first unlocked one to open
  const retrieveQueueWorkItems = async () => {
    getQueueWorkItems(queueId)
      .then((result) => {
        const first = result.find((workItem) =>
          [null, username].includes(workItem.lockedBy)
        );

        if (first) {
          openWorkItem(processId, queueId, first.workItemReferenceId);
        } else {
          navigate('/');
        }
      })
      .catch((error: FetchError) => {
        toast.error(error.message);
        navigate('/');
      });
  };

  const openMode = getStoredOpenMode();

  // Determine which work item to open
  useEffect(() => {
    if (openMode === 'inbox') {
      retrieveInboxWorkItems();
    } else if (openMode === 'queue' && processId && queueId) {
      retrieveQueueWorkItems();
    } else {
      navigate('/');
    }
  }, [openMode]);

  const { t } = useTranslation(undefined, {
    keyPrefix: 'pages.auto_open',
  });

  return (
    <div
      className={
        'd-flex flex-grow-1 flex-column gap-2 justify-content-center align-items-center'
      }
    >
      <Spinner animation={'border'} role={'status'} variant={'primary'}>
        <span className={'visually-hidden'}>{t('spinner.default')}...</span>
      </Spinner>
      <div>{t('text')}...</div>
    </div>
  );
};
