import React from 'react';
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Table, TableColumn } from '@/components/ui/Table';

interface TestRow {
  id: string;
  name: string;
  email: string;
}

const columns: TableColumn<TestRow>[] = [
  { key: 'name', header: 'Name', sortable: true },
  { key: 'email', header: 'E-Mail', sortable: true },
  { key: 'id', header: 'ID', sortable: false },
];

const data: TestRow[] = [
  { id: '1', name: 'Anna Schmidt', email: 'anna@test.de' },
  { id: '2', name: 'Max Müller', email: 'max@test.de' },
  { id: '3', name: 'Lisa Weber', email: 'lisa@test.de' },
];

describe('Table', () => {
  it('renders all rows and headers', () => {
    render(<Table columns={columns} data={data} rowKey={(r) => r.id} />);
    expect(screen.getByText('Anna Schmidt')).toBeInTheDocument();
    expect(screen.getByText('Max Müller')).toBeInTheDocument();
    expect(screen.getByText('Lisa Weber')).toBeInTheDocument();
    expect(screen.getByText('Name')).toBeInTheDocument();
    expect(screen.getByText('E-Mail')).toBeInTheDocument();
  });

  it('sortable headers have role=button and aria-label', () => {
    render(<Table columns={columns} data={data} rowKey={(r) => r.id} />);
    const nameHeader = screen.getByRole('button', { name: /Name/ });
    expect(nameHeader).toBeInTheDocument();
  });

  it('clicking sortable header sorts ascending then descending', () => {
    render(<Table columns={columns} data={data} rowKey={(r) => r.id} />);
    const nameHeader = screen.getByRole('button', { name: /Name/ });
    fireEvent.click(nameHeader);
    // ascending: Anna, Lisa, Max
    const rows = screen.getAllByRole('row');
    expect(rows[1]).toHaveTextContent('Anna Schmidt');
    expect(rows[3]).toHaveTextContent('Max Müller');
    fireEvent.click(nameHeader);
    // descending: Max, Lisa, Anna
    const rowsDesc = screen.getAllByRole('row');
    expect(rowsDesc[1]).toHaveTextContent('Max Müller');
    expect(rowsDesc[3]).toHaveTextContent('Anna Schmidt');
  });

  it('aria-sort updates on sort', () => {
    render(<Table columns={columns} data={data} rowKey={(r) => r.id} />);
    const nameHeader = screen.getByRole('button', { name: /Name/ });
    expect(nameHeader.closest('th')).toHaveAttribute('aria-sort', 'none');
    fireEvent.click(nameHeader);
    expect(nameHeader.closest('th')).toHaveAttribute('aria-sort', 'ascending');
  });

  it('shows empty message when no data', () => {
    render(<Table columns={columns} data={[]} rowKey={(r) => r.id} emptyMessage="Keine Daten" />);
    expect(screen.getByText('Keine Daten')).toBeInTheDocument();
  });

  it('shows loading state', () => {
    render(<Table columns={columns} data={[]} rowKey={(r) => r.id} loading={true} />);
    expect(screen.getByText('Wird geladen...')).toBeInTheDocument();
  });
});
