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

const mockUploadFile = vi.fn();

vi.mock('@/api/dms', () => ({
  uploadFile: (...args: unknown[]) => mockUploadFile(...args),
}));

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

beforeEach(() => {
  vi.clearAllMocks();
  mockUploadFile.mockResolvedValue({ id: 'file1', name: 'test.pdf' });
});

describe('UploadDropzone', () => {
  it('renders the dropzone area', () => {
    render(<UploadDropzone folderId={null} onUploaded={vi.fn()} />);
    expect(screen.getByTestId('upload-dropzone')).toBeInTheDocument();
  });

  it('renders drag-and-drop instruction text', () => {
    render(<UploadDropzone folderId={null} onUploaded={vi.fn()} />);
    expect(screen.getByText('Dateien hierher ziehen oder klicken zum Auswaehlen')).toBeInTheDocument();
  });

  it('opens file picker on click', () => {
    render(<UploadDropzone folderId={null} onUploaded={vi.fn()} />);
    const dropzone = screen.getByTestId('upload-dropzone');
    const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
    expect(input).toBeTruthy();
    expect(input.multiple).toBe(true);
  });

  it('uploads files when input changes', async () => {
    const onUploaded = vi.fn();
    render(<UploadDropzone folderId="f1" onUploaded={onUploaded} />);
    const input = screen.getByTestId('upload-dropzone').querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File(['test content'], 'report.pdf', { type: 'application/pdf' });
    fireEvent.change(input, { target: { files: [file] } });
    await waitFor(() => {
      expect(mockUploadFile).toHaveBeenCalledWith(file, 'f1');
    });
    await waitFor(() => {
      expect(onUploaded).toHaveBeenCalled();
    });
  });

  it('shows upload progress after file selection', async () => {
    render(<UploadDropzone folderId={null} onUploaded={vi.fn()} />);
    const input = screen.getByTestId('upload-dropzone').querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File(['data'], 'doc.pdf', { type: 'application/pdf' });
    fireEvent.change(input, { target: { files: [file] } });
    await waitFor(() => {
      expect(screen.getByTestId('upload-progress-list')).toBeInTheDocument();
    });
  });
});
