import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { DatevExport } from '@/components/sales/DatevExport';

// Mock the datev lib
vi.mock('@/lib/datev', () => ({
  createDatevExport: vi.fn(),
  listDatevExports: vi.fn(),
  getDatevDownloadUrl: vi.fn().mockReturnValue('http://test/datev.csv'),
}));

import { listDatevExports, createDatevExport } from '@/lib/datev';

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

  it('renders DATEV export page with title', async () => {
    vi.mocked(listDatevExports).mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      page_size: 20,
    });

    render(<DatevExport />);
    expect(screen.getByText('DATEV Export')).toBeInTheDocument();
    expect(screen.getByTestId('datev-export')).toBeInTheDocument();
  });

  it('has date range inputs', async () => {
    vi.mocked(listDatevExports).mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      page_size: 20,
    });

    render(<DatevExport />);
    expect(screen.getByTestId('datev-start-date')).toBeInTheDocument();
    expect(screen.getByTestId('datev-end-date')).toBeInTheDocument();
  });

  it('has create export button', async () => {
    vi.mocked(listDatevExports).mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      page_size: 20,
    });

    render(<DatevExport />);
    expect(screen.getByTestId('datev-create-btn')).toBeInTheDocument();
  });

  it('shows empty state when no exports', async () => {
    vi.mocked(listDatevExports).mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      page_size: 20,
    });

    render(<DatevExport />);
    await waitFor(() => {
      expect(screen.getByTestId('datev-empty')).toBeInTheDocument();
    });
  });

  it('displays exports in table', async () => {
    const mockExport = {
      id: 'test-export-id',
      start_date: '2025-01-01',
      end_date: '2025-01-31',
      total_amount: 95000,
      created_at: '2025-02-01T10:00:00Z',
    };
    vi.mocked(listDatevExports).mockResolvedValue({
      items: [mockExport],
      total: 1,
      page: 1,
      page_size: 20,
    });

    render(<DatevExport />);
    await waitFor(() => {
      expect(screen.getByTestId('datev-download-test-export-id')).toBeInTheDocument();
    });
  });
});
