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

vi.mock('@/api/dms', () => ({
  fetchFolders: vi.fn().mockResolvedValue([
    { id: 'f1', name: 'Vertraege', parent_id: null, created_by: 'u1', children: [] },
    { id: 'f2', name: 'Rechnungen', parent_id: null, created_by: 'u1', children: [] },
  ]),
  createFolder: vi.fn().mockResolvedValue({ id: 'f3', name: 'Neuer Ordner', parent_id: null, created_by: 'u1' }),
  deleteFile: vi.fn().mockResolvedValue(undefined),
  searchFiles: vi.fn().mockResolvedValue({ files: [], total: 0 }),
}));

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

import { DmsPage } from '@/pages/Dms';

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

beforeEach(() => {
  vi.clearAllMocks();
});

describe('DmsPage', () => {
  it('renders the DMS page with title', () => {
    renderWithRouter();
    expect(screen.getByTestId('dms-page')).toBeInTheDocument();
  });

  it('renders folder tree container', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('folder-tree-container')).toBeInTheDocument();
    });
  });

  it('renders file grid container', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('file-grid-container')).toBeInTheDocument();
    });
  });

  it('renders folder tree with folders after loading', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByText('Vertraege')).toBeInTheDocument();
      expect(screen.getByText('Rechnungen')).toBeInTheDocument();
    });
  });

  it('shows upload button and toggles upload dropzone', async () => {
    renderWithRouter();
    const uploadBtn = screen.getByText('Hochladen');
    expect(uploadBtn).toBeInTheDocument();
    fireEvent.click(uploadBtn);
    await waitFor(() => {
      expect(screen.getByTestId('upload-dropzone')).toBeInTheDocument();
    });
  });

  it('shows new folder button and toggles form', async () => {
    renderWithRouter();
    const folderBtn = screen.getByText('Neuer Ordner');
    expect(folderBtn).toBeInTheDocument();
    fireEvent.click(folderBtn);
    await waitFor(() => {
      expect(screen.getByTestId('new-folder-form')).toBeInTheDocument();
    });
  });

  it('renders trash link', async () => {
    renderWithRouter();
    expect(screen.getByText('Papierkorb')).toBeInTheDocument();
  });

  it('renders search input', async () => {
    renderWithRouter();
    expect(screen.getByLabelText('Dateien durchsuchen')).toBeInTheDocument();
  });
});
