import { render } from '@testing-library/react';
import { act, renderHook } from '@testing-library/react-hooks';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageBar } from '../../MessageBar/MessageBar';
import { StationMessage, useStationMessage } from './useStationMessage';

vi.mock('../../MessageBar/MessageBar', () => ({
  MessageBar: vi.fn(() => null),
}));

describe('useStationMessage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should initialize with undefined station message', () => {
    const { result } = renderHook(() => useStationMessage());

    expect(result.current.stationMessage).toBeUndefined();
  });

  it('should set a station message', () => {
    const { result } = renderHook(() => useStationMessage());
    const message: StationMessage = {
      type: 'error',
      title: 'Error',
      body: 'An error occurred',
      canClose: true,
    };

    act(() => {
      result.current.setStationMessage(message);
    });

    expect(result.current.stationMessage).toEqual(message);
  });

  it('should clear the station message when onClose is called', () => {
    const { result } = renderHook(() => useStationMessage());
    const message: StationMessage = {
      type: 'error',
      title: 'Error',
      body: 'An error occurred',
      canClose: true,
    };

    act(() => {
      result.current.setStationMessage(message);
    });

    act(() => {
      result.current.StationMessage.props.children.props.onClose();
    });

    expect(result.current.stationMessage).toBeUndefined();
  });

  it('should render MessageBar with correct props', () => {
    const { result } = renderHook(() => useStationMessage());
    const message: StationMessage = {
      type: 'error',
      title: 'Error',
      body: 'An error occurred',
      canClose: true,
    };

    act(() => {
      result.current.setStationMessage(message);
    });

    render(result.current.StationMessage);

    expect(MessageBar).toHaveBeenCalledWith(
      expect.objectContaining({
        type: message.type,
        title: message.title,
        onClose: expect.any(Function),
        onRetry: message.onRetry,
        children: message.body,
      }),
      {},
    );
  });

  it('should not render MessageBar when stationMessage is undefined', () => {
    const { result } = renderHook(() => useStationMessage());

    render(result.current.StationMessage);

    expect(MessageBar).not.toHaveBeenCalled();
  });
});
