import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react-native';
import { api } from '@/services/api';

// Mock dependencies
jest.mock('@/services/api');
jest.mock('expo-router', () => ({
  useLocalSearchParams: () => ({ id: '1' }),
  router: { back: jest.fn(), push: jest.fn() },
}));
jest.mock('@/contexts/BeneficiaryContext', () => ({
  useBeneficiary: () => ({
    currentBeneficiary: { id: 1, name: 'Test User' },
  }),
}));
jest.mock('@/contexts/BLEContext', () => ({
  useBLE: () => ({
    isBLEAvailable: true,
  }),
}));

// Import the screen after mocks are set up
import EquipmentScreen from '@/app/(tabs)/beneficiaries/[id]/equipment';

describe('EquipmentScreen - Error Handling', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('displays error message when API call fails', async () => {
    const mockError = { ok: false, error: { message: 'Network error' } };
    (api.getDevicesForBeneficiary as jest.Mock).mockResolvedValue(mockError);

    const { getByText, findByText } = render(<EquipmentScreen />);

    await waitFor(() => {
      expect(findByText('Network error')).toBeTruthy();
    });
  });

  it('displays retry button when error occurs', async () => {
    const mockError = { ok: false, error: { message: 'Failed to load sensors' } };
    (api.getDevicesForBeneficiary as jest.Mock).mockResolvedValue(mockError);

    const { findByText } = render(<EquipmentScreen />);

    await waitFor(() => {
      expect(findByText('Try Again')).toBeTruthy();
    });
  });

  it('retries loading sensors when retry button is pressed', async () => {
    const mockError = { ok: false, error: { message: 'Failed to load sensors' } };
    const mockSuccess = { ok: true, data: [] };

    (api.getDevicesForBeneficiary as jest.Mock)
      .mockResolvedValueOnce(mockError)
      .mockResolvedValueOnce(mockSuccess);

    const { findByText, queryByText } = render(<EquipmentScreen />);

    // Wait for error to appear
    await waitFor(() => {
      expect(findByText('Try Again')).toBeTruthy();
    });

    // Press retry button
    const retryButton = await findByText('Try Again');
    fireEvent.press(retryButton);

    // Wait for error to disappear after successful retry
    await waitFor(() => {
      expect(queryByText('Failed to load sensors')).toBeNull();
    });

    // Verify API was called twice
    expect(api.getDevicesForBeneficiary).toHaveBeenCalledTimes(2);
  });

  it('displays generic error message for unknown errors', async () => {
    (api.getDevicesForBeneficiary as jest.Mock).mockRejectedValue(
      new Error('Unknown error')
    );

    const { findByText } = render(<EquipmentScreen />);

    await waitFor(() => {
      expect(findByText(/Unknown error|Failed to load sensors/)).toBeTruthy();
    });
  });
});
