import * as React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import EditComponent from './edit';
import type { TitleSelection } from '../types';

// Mock WordPress dependencies
vi.mock('@wordpress/block-editor', () => ({
  useBlockProps: vi.fn(() => ({})),
  InspectorControls: vi.fn(({ children }) => <div>{children}</div>),
}));

vi.mock('@wordpress/components', () => ({
  Button: vi.fn(({ children, onClick }) => <button onClick={onClick}>{children}</button>),
  PanelBody: vi.fn(({ children }) => <div>{children}</div>),
  CheckboxControl: vi.fn(({ label, checked, onChange }) => (
    <label>
      {label}
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
    </label>
  )),
  Placeholder: vi.fn(({ children }) => <div>{children}</div>),
  VStack: vi.fn(({ children }) => <div>{children}</div>),
  InputControl: vi.fn(({ value, suffix }) => (
    <div>
      <input value={value} readOnly />
      {suffix}
    </div>
  )),
}));

vi.mock('@wordpress/i18n', () => ({
  __: vi.fn((text) => text),
  sprintf: vi.fn((text, arg) => `${text} ${arg}`),
}));

vi.mock('../context/config', () => ({
  default: {
    settings: {
      apiKey: 'test-api-key',
      settingsUrl: 'http://example.com/settings',
    },
  },
}));

vi.mock('../components/title-controls/TitleControls', () =>
  vi.fn(({ titleSelection, onTitleSelectionChange }) => (
    <div>
      <input
        value={titleSelection?.id || ''}
        onChange={(e) => onTitleSelectionChange({ id: e.target.value })}
      />
    </div>
  ))
);

vi.mock('../components/widget-preview/WidgetPreview', () =>
  vi.fn(() => <div>Widget Preview</div>)
);

vi.mock('./save', () => ({
  generateShortcode: vi.fn((attributes) => `[justwatch id="${attributes.id}"]`),
}));

describe.skip('EditComponent', () => {
  const setAttributes = vi.fn();
  const defaultAttributes: TitleSelection = {
    id: '123',
    objectType: 'movie',
  };

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

  it('renders the editing placeholder when no ID is provided', () => {
    render(
      <EditComponent
        attributes={{ id: '', objectType: 'movie' }}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    expect(screen.getByText('Insert Justwatch Widget')).toBeInTheDocument();
    expect(screen.getByText('Enter a movie or TV show title to search for it on Justwatch.')).toBeInTheDocument();
  });

  it('renders the preview when an ID is provided', () => {
    render(
      <EditComponent
        attributes={defaultAttributes}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    expect(screen.getByText('Widget Preview')).toBeInTheDocument();
  });

  it('toggles the shortcode view when the checkbox is clicked', async () => {
    render(
      <EditComponent
        attributes={defaultAttributes}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    const checkbox = screen.getByLabelText('View Shortcode');
    fireEvent.click(checkbox);

    await waitFor(() => {
      expect(screen.getByDisplayValue('[justwatch id="123"]')).toBeInTheDocument();
    });
  });

  it('copies the shortcode to the clipboard when the copy button is clicked', async () => {
    Object.assign(navigator, {
      clipboard: {
        writeText: vi.fn().mockResolvedValue(undefined),
      },
    });

    render(
      <EditComponent
        attributes={defaultAttributes}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    const checkbox = screen.getByLabelText('View Shortcode');
    fireEvent.click(checkbox);

    const copyButton = screen.getByRole('button', { name: 'clipboard' });
    fireEvent.click(copyButton);

    await waitFor(() => {
      expect(navigator.clipboard.writeText).toHaveBeenCalledWith('[justwatch id="123"]');
      expect(screen.getByRole('button', { name: 'yes' })).toBeInTheDocument();
    });
  });

  it('updates the title selection when a new title is selected', async () => {
    render(
      <EditComponent
        attributes={{ id: '', objectType: 'movie' }}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    const input = screen.getByRole('textbox');
    fireEvent.change(input, { target: { value: '456' } });

    const confirmButton = screen.getByText('Confirm');
    fireEvent.click(confirmButton);

    await waitFor(() => {
      expect(setAttributes).toHaveBeenCalledWith({
        id: '456',
        objectType: undefined,
        meta: undefined,
      });
    });
  });

  it('shows an error message when the API key is missing', () => {
    const config = {
      settings: {
        apiKey: '',
      },
    }
    vi.mocked(config).settings.apiKey = '';

    render(
      <EditComponent
        attributes={defaultAttributes}
        setAttributes={setAttributes}
        clientId="test-client-id"
        isSelected={false}
        context={{}}
        className=""
      />
    );

    expect(screen.getByText('Please provide a valid Justwatch API key in the plugin settings')).toBeInTheDocument();
  });
});