import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { ThemeProvider } from 'styled-components';
import { I18nextProvider } from 'react-i18next';
import i18n from '@/locales/i18n';
import { LocaleProvider } from '@/app/providers/LocaleProvider';
import { lightTheme } from '@/styles/theme';
import { MessageAttachments } from '@/features/tickets/components/MessageAttachments';
import type { TicketAttachment } from '@/features/tickets/types/ticket.types';
import {
  downloadAttachmentFile,
  openAttachmentInNewTab,
} from '@/shared/utils/fetchAttachment';

vi.mock('@/shared/utils/fetchAttachment', () => ({
  fetchAttachmentBlob: vi.fn(),
  openAttachmentInNewTab: vi.fn(),
  downloadAttachmentFile: vi.fn(),
}));

const attachments: TicketAttachment[] = [
  {
    id: 'att-1',
    file_name: 'screenshot.png',
    file_size: 2048,
    mime_type: 'image/png',
  },
  {
    id: 'att-2',
    file_name: 'report.pdf',
    file_size: 4096,
    mime_type: 'application/pdf',
  },
];

function renderAttachments() {
  return render(
    <I18nextProvider i18n={i18n}>
      <LocaleProvider>
        <ThemeProvider theme={lightTheme}>
          <MessageAttachments attachments={attachments} accentColor="#3B82F6" />
        </ThemeProvider>
      </LocaleProvider>
    </I18nextProvider>,
  );
}

describe('MessageAttachments', () => {
  it('shows view and download actions beside each attachment', async () => {
    const user = userEvent.setup();
    renderAttachments();

    expect(screen.getByRole('button', { name: /View: screenshot\.png/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Download: screenshot\.png/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /View: report\.pdf/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Download: report\.pdf/i })).toBeInTheDocument();

    await user.click(screen.getByRole('button', { name: /View: report\.pdf/i }));
    expect(openAttachmentInNewTab).toHaveBeenCalledWith(
      attachments[1],
      { inline: true },
    );

    await user.click(screen.getByRole('button', { name: /Download: report\.pdf/i }));
    expect(downloadAttachmentFile).toHaveBeenCalledWith(attachments[1]);

    expect(screen.getByText('screenshot.png')).toBeInTheDocument();
    expect(screen.getByText('report.pdf')).toBeInTheDocument();
    expect(screen.queryByText('View')).not.toBeInTheDocument();
    expect(screen.queryByText('Download')).not.toBeInTheDocument();
  });
});
