import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ApkList from '../ApkList';
import useSWR from 'swr';

jest.mock('swr');

describe('ApkList', () => {
  const mockApks = [
    {
      name: 'ft_timeshift_0_42_57ef3a60d.apk',
      environment: 'dev',
      commit: '57ef3a60d',
      size: 15728640,
      modifiedAt: '2026-03-04T14:30:00.000Z',
      downloadUrl: '/api/download?project=FT&version=0_42&filename=ft_timeshift_0_42_57ef3a60d.apk',
    },
    {
      name: 'ft_0_42_ff9ff3441.apk',
      environment: 'product',
      commit: 'ff9ff3441',
      size: 15728640,
      modifiedAt: '2026-03-04T14:30:00.000Z',
      downloadUrl: '/api/download?project=FT&version=0_42&filename=ft_0_42_ff9ff3441.apk',
    },
    {
      name: 'ft_sandbox_0_42_57ef3a60d.apk',
      environment: 'sandbox',
      commit: '57ef3a60d',
      size: 15728640,
      modifiedAt: '2026-03-04T14:30:00.000Z',
      downloadUrl: '/api/download?project=FT&version=0_42&filename=ft_sandbox_0_42_57ef3a60d.apk',
    },
  ];

  beforeEach(() => {
    (useSWR as jest.Mock).mockReturnValue({
      data: mockApks,
      isLoading: false,
      error: null,
    });
  });

  it('should render all 4 tabs', () => {
    render(<ApkList project="FT" version="0_42" commitId="" />);

    expect(screen.getByText(/dev/)).toBeInTheDocument();
    expect(screen.getByText(/product/)).toBeInTheDocument();
    expect(screen.getByText(/sandbox/)).toBeInTheDocument();
    expect(screen.getByText(/other/)).toBeInTheDocument();
  });

  it('should switch tabs correctly', () => {
    render(<ApkList project="FT" version="0_42" commitId="" />);

    const devTab = screen.getByText(/dev/);
    fireEvent.click(devTab);

    expect(screen.getByText('57ef3a60d')).toBeInTheDocument();
  });

  it('should show loading state', () => {
    (useSWR as jest.Mock).mockReturnValue({
      data: null,
      isLoading: true,
      error: null,
    });

    render(<ApkList project="FT" version="0_42" commitId="" />);

    expect(screen.getByText('加载中...')).toBeInTheDocument();
  });

  it('should show error state', () => {
    (useSWR as jest.Mock).mockReturnValue({
      data: null,
      isLoading: false,
      error: new Error('API error'),
    });

    render(<ApkList project="FT" version="0_42" commitId="" />);

    expect(screen.getByText('加载失败，请重试')).toBeInTheDocument();
  });
});
