import { render, screen } from '@testing-library/react';
import { ThemeProvider } from '../../theme';

jest.mock('next-intl', () => ({ useTranslations: () => (k: string, v?: Record<string, unknown>) => (v ? `${k}` : k), useLocale: () => 'en' }));
jest.mock('notistack', () => ({ useSnackbar: () => ({ enqueueSnackbar: jest.fn() }) }));

const mockUsePreview = jest.fn();
const mutation = () => ({ mutate: jest.fn(), isPending: false });
jest.mock('@/services/refunds', () => ({
  useRefundPreview: (...a: unknown[]) => mockUsePreview(...a),
  useInitiateRefund: () => mutation(),
  useApproveRefund: () => mutation(),
  useRejectRefund: () => mutation(),
}));

import RefundPanel from './RefundPanel';

// Reconciles: fee 1500000 + payout 8500000 = 10000000 amount.
const PREVIEW = {
  bookingId: 42,
  refundPercentageApplied: 1,
  amountIrr: '10000000',
  platformFeeRefundedIrr: '1500000',
  nursePayoutRefundedIrr: '8500000',
  refundChannel: 'psp_card' as const,
  expectedCustomerRefundEta: null,
  willCreateClawback: false,
  cancellationPolicyCode: null,
};

describe('<RefundPanel/>', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);
  afterEach(() => mockUsePreview.mockReset());

  it('renders the server-computed reconciling decomposition', () => {
    const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
    mockUsePreview.mockReturnValue({ data: PREVIEW, isLoading: false, isError: false });
    wrap(<RefundPanel bookingId={42} ticketId={9} />);
    expect(screen.getByText('refund_preview_title')).toBeInTheDocument();
    expect(screen.getByText('refund_initiate')).toBeInTheDocument();
    expect(errorSpy).not.toHaveBeenCalledWith(expect.stringContaining('must reconcile'));
    errorSpy.mockRestore();
  });

  it('shows the clawback notice when the nurse was already paid', () => {
    mockUsePreview.mockReturnValue({ data: { ...PREVIEW, willCreateClawback: true }, isLoading: false, isError: false });
    wrap(<RefundPanel bookingId={42} ticketId={9} />);
    expect(screen.getByText('refund_clawback_notice')).toBeInTheDocument();
  });

  it('shows a loading skeleton while the preview loads', () => {
    mockUsePreview.mockReturnValue({ data: undefined, isLoading: true, isError: false });
    const { container } = wrap(<RefundPanel bookingId={42} ticketId={9} />);
    expect(container.querySelector('.MuiSkeleton-root')).toBeInTheDocument();
  });
});
