import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { ImageCropper } from './ImageCropper';

// Mock react-easy-crop
vi.mock('react-easy-crop', () => ({
  default: ({ image, onCropChange, onCropComplete }: any) => (
    <div data-testid="cropper">
      <img src={image} alt="cropper" />
      <button onClick={() => onCropChange({ x: 10, y: 10 })}>
        Change Crop
      </button>
      <button
        onClick={() =>
          onCropComplete({}, { x: 0, y: 0, width: 100, height: 100 })
        }
      >
        Complete Crop
      </button>
    </div>
  ),
}));

describe('ImageCropper Component', () => {
  const mockOnCancel = vi.fn();
  const mockOnCropComplete = vi.fn();

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

  it('renders cropper with image', () => {
    render(
      <ImageCropper
        imageSrc="test.jpg"
        aspectRatio={1}
        onCancel={mockOnCancel}
        onCropComplete={mockOnCropComplete}
      />,
    );

    expect(screen.getByTestId('cropper')).toBeInTheDocument();
    expect(screen.getByText('Edit Image')).toBeInTheDocument();
  });

  it('calls onCancel when cancel button is clicked', () => {
    render(
      <ImageCropper
        imageSrc="test.jpg"
        aspectRatio={1}
        onCancel={mockOnCancel}
        onCropComplete={mockOnCropComplete}
      />,
    );

    const cancelButton = screen.getByText('Cancel');
    fireEvent.click(cancelButton);

    expect(mockOnCancel).toHaveBeenCalled();
  });

  it('calls onCropComplete when save button is clicked', () => {
    render(
      <ImageCropper
        imageSrc="test.jpg"
        aspectRatio={1}
        onCancel={mockOnCancel}
        onCropComplete={mockOnCropComplete}
      />,
    );

    // First complete a crop
    const completeButton = screen.getByText('Complete Crop');
    fireEvent.click(completeButton);

    // Then save
    const saveButton = screen.getByText('Apply Crop');
    fireEvent.click(saveButton);

    expect(mockOnCropComplete).toHaveBeenCalled();
  });

  it('renders with circular crop when circularCrop is true', () => {
    render(
      <ImageCropper
        imageSrc="test.jpg"
        aspectRatio={1}
        onCancel={mockOnCancel}
        onCropComplete={mockOnCropComplete}
        circularCrop={true}
      />,
    );

    expect(screen.getByTestId('cropper')).toBeInTheDocument();
  });
});
