/**
 * @file RefreshButton.tsx - Status-aware refresh button that displays color-coded status for data retrieval operations.
 *
 * Cycles through four visual states:
 * - none : idle / default (primary, arrow icon)
 * - start : refresh in progress (primary, arrow icon, loading text)
 * - success : refresh succeeded (success, check icon, auto-resets after 5s)
 * - error : refresh failed (danger, exclamation icon, auto-resets after 5s)
 *
 * The parent component owns the status state and listens for the "start" transition to kick off the actual data-fetching logic.
 */

import { Icon } from './Icon.tsx';
import { Button } from 'react-bootstrap';
import { type FC, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';

/** The four lifecycle states the refresh button can be in */
export type RefreshButtonStatus = 'none' | 'start' | 'success' | 'error';

/**
 * Props for the RefreshButton component.
 */
interface RefreshButtonProps {
  /** Current lifecycle state that drives the button's appearance */
  refreshStatus: RefreshButtonStatus;

  /** Setter used to transition between states; the parent should watch for "start" to initiate a data refresh */
  setRefreshStatus: (refreshStatus: RefreshButtonStatus) => void;

  /** Optionally disable the button */
  disabled?: boolean;
}

/**
 * Status-aware button that visually communicates the outcome of a refresh operation.
 * Clicking the button sets refreshStatus to "start", signalling the parent to begin a refresh.
 * Once the parent sets the status to "success" or "error", the button auto-resets to "none" after 5 seconds.
 */
export const RefreshButton: FC<RefreshButtonProps> = ({
  refreshStatus,
  setRefreshStatus,
  disabled = false,
}: RefreshButtonProps) => {
  const refreshButton = useRef<HTMLButtonElement | null>(null);

  // Auto-transition back to refreshStatus = 'none' after 5 seconds
  useEffect(() => {
    if (refreshButton.current && ['success', 'error'].includes(refreshStatus)) {
      setTimeout(() => {
        setRefreshStatus('none');
      }, 5e3);
    }
  }, [refreshStatus, setRefreshStatus]);

  const { t } = useTranslation(undefined, {
    keyPrefix: 'components.refresh_button',
  });

  return (
    <Button
      ref={refreshButton}
      variant={
        refreshStatus === 'success'
          ? 'success'
          : refreshStatus === 'error'
            ? 'danger'
            : 'primary'
      }
      onClick={() => {
        setRefreshStatus('start');
      }}
      disabled={disabled}
    >
      <div className={'d-flex align-items-center justify-content-center'}>
        <Icon
          iconName={
            refreshStatus === 'success'
              ? 'CheckCircle'
              : refreshStatus === 'error'
                ? 'ExclamationCircle'
                : 'ArrowClockwise'
          }
          size={20}
        />
        <span className={'ms-2'}>
          {refreshStatus === 'success'
            ? `${t('success')}`
            : refreshStatus === 'error'
              ? `${t('error')}`
              : refreshStatus === 'start'
                ? `${t('start')}...`
                : `${t('default')}`}
        </span>
      </div>
    </Button>
  );
};
