import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import CopyLinkButton from '../src/components/CopyLinkButton';

// Mock the Clipboard API
Object.defineProperty(navigator, 'clipboard', {
  value: {
    writeText: jest.fn(),
  },
  writable: true,
});

describe('CopyLinkButton', () => {
  const testLink = 'http://localhost:3000/session/123';

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

  test('renders with "Copy Link" text and copy icon initially', () => {
    render(<CopyLinkButton linkToCopy={testLink} />);
    expect(screen.getByRole('button', { name: /copy link/i })).toBeInTheDocument();
    expect(screen.getByTestId('ContentCopyIcon')).toBeInTheDocument();
  });

  test('copies the link to clipboard and shows "Copied!" with check icon on click', async () => {
    render(<CopyLinkButton linkToCopy={testLink} />);
    const copyButton = screen.getByRole('button', { name: /copy link/i });

    fireEvent.click(copyButton);

    expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1);
    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(testLink);

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /copied!/i })).toBeInTheDocument();
      expect(screen.getByTestId('CheckCircleOutlineIcon')).toBeInTheDocument();
    });
  });

  test('reverts to "Copy Link" and copy icon after 3 seconds', async () => {
    jest.useFakeTimers();
    render(<CopyLinkButton linkToCopy={testLink} />);
    const copyButton = screen.getByRole('button', { name: /copy link/i });

    fireEvent.click(copyButton);

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /copied!/i })).toBeInTheDocument();
    });

    jest.advanceTimersByTime(3000);

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /copy link/i })).toBeInTheDocument();
      expect(screen.getByTestId('ContentCopyIcon')).toBeInTheDocument();
    });
    jest.useRealTimers();
  });

  test('logs an error if clipboard.writeText fails', async () => {
    const errorMessage = 'Failed to write to clipboard';
    (navigator.clipboard.writeText as jest.Mock).mockRejectedValueOnce(new Error(errorMessage));
    const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

    render(<CopyLinkButton linkToCopy={testLink} />);
    const copyButton = screen.getByRole('button', { name: /copy link/i });

    fireEvent.click(copyButton);

    await waitFor(() => {
      expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to copy link:', expect.any(Error));
    });

    consoleErrorSpy.mockRestore();
  });
});
