import React from 'react';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { CompaniesListPage } from '@/pages/CompaniesList';

const mockCompanies = [
  { id: '1', name: 'TestCorp GmbH', email: 'info@test.de', phone: '+49 30 123', industry: 'IT', account_number: 'K-001', created_at: '2025-01-01T00:00:00Z', updated_at: '2025-01-01T00:00:00Z' },
  { id: '2', name: 'Müller AG', email: 'kontakt@mueller.de', phone: '+49 89 987', industry: 'Logistik', account_number: 'K-002', created_at: '2025-01-02T00:00:00Z', updated_at: '2025-01-02T00:00:00Z' },
];

let mockData: any = { items: mockCompanies, total: 2 };
let mockIsLoading = false;

vi.mock('@/api/hooks', () => ({
  useCompanies: () => ({ data: mockData, isLoading: mockIsLoading }),
  useCompanyExport: () => ({ mutateAsync: vi.fn().mockResolvedValue(new Blob(['csv'], { type: 'text/csv' })), isPending: false }),
  useDeleteCompany: () => ({ mutateAsync: vi.fn(), isPending: false }),
  useCompanyImport: () => ({ mutateAsync: vi.fn(), isPending: false }),
}));

vi.mock('@/components/ui/Toast', () => ({
  useToast: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
}));

vi.mock('@/components/shared/UnsavedChangesGuard', () => ({
  UnsavedChangesGuard: () => null,
}));

function renderWithRouter() {
  return render(<MemoryRouter><CompaniesListPage /></MemoryRouter>);
}

beforeEach(() => {
  mockData = { items: mockCompanies, total: 2 };
  mockIsLoading = false;
});

afterEach(() => {
  mockData = { items: mockCompanies, total: 2 };
  mockIsLoading = false;
});

describe('CompaniesListPage', () => {
  it('renders the page with title', () => {
    renderWithRouter();
    expect(screen.getByTestId('companies-list-page')).toBeInTheDocument();
  });

  it('renders DataGrid for company list (TanStack Table)', () => {
    renderWithRouter();
    expect(screen.getByTestId('companies-grid')).toBeInTheDocument();
  });

  it('renders company data in grid', () => {
    renderWithRouter();
    expect(screen.getByText('TestCorp GmbH')).toBeInTheDocument();
    expect(screen.getByText('Müller AG')).toBeInTheDocument();
  });

  it('renders search input', () => {
    renderWithRouter();
    expect(screen.getByLabelText(/Suchen/)).toBeInTheDocument();
  });

  it('renders create button', () => {
    renderWithRouter();
    expect(screen.getByText('Firma erstellen')).toBeInTheDocument();
  });

  it('renders import button', () => {
    renderWithRouter();
    expect(screen.getByText('CSV importieren')).toBeInTheDocument();
  });

  it('renders export button', () => {
    renderWithRouter();
    expect(screen.getByText('CSV exportieren')).toBeInTheDocument();
  });

  it('renders table headers with sortable columns', () => {
    renderWithRouter();
    expect(screen.getByText('Firmenname')).toBeInTheDocument();
    expect(screen.getByText('Branche')).toBeInTheDocument();
  });

  it('shows empty state when no companies and no search', () => {
    mockData = { items: [], total: 0 };
    renderWithRouter();
    expect(screen.getByText('Keine Firmen vorhanden')).toBeInTheDocument();
    expect(screen.getByText('Firma erstellen')).toBeInTheDocument();
    mockData = { items: mockCompanies, total: 2 };
  });

  it('shows no results message when search yields nothing', async () => {
    renderWithRouter();
    const searchInput = screen.getByLabelText(/Suchen/);
    fireEvent.change(searchInput, { target: { value: 'xyz' } });
    mockData = { items: [], total: 0 };
    // With search text but no results, grid should show no results message
    await waitFor(() => {
      expect(screen.getByText('Keine Ergebnisse gefunden')).toBeInTheDocument();
    });
  });

  it('clicking sort header toggles sort direction', () => {
    renderWithRouter();
    const nameHeader = screen.getByText('Firmenname');
    const th = nameHeader.closest('th');
    expect(th).toHaveAttribute('aria-sort', 'none');
    fireEvent.click(nameHeader);
    expect(th).toHaveAttribute('aria-sort', 'ascending');
  });

  it('opens import dialog when import button clicked', () => {
    renderWithRouter();
    fireEvent.click(screen.getByText('CSV importieren'));
    expect(screen.getByTestId('csv-import-dialog')).toBeInTheDocument();
  });
});
