import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import PhotoPostWizard from '@/features/photopost/components/PhotoPostWizard';

// Mock event media so presenter doesn't fetch
vi.mock('@/features/event/api/getEventMedia', () => ({
  getEventMedia: vi.fn().mockResolvedValue([]),
}));

// Silence console.error noise (optional)
const ce = console.error;
console.error = (...args: any[]) => {};

function makeOutput() {
  return {
    output: {
      linkedin: [{ text: [{ de: 'DE post', en: 'EN post', es: 'ES post' }] }],
      twitter: [{ text: [{ de: 'DE tw', en: 'EN tw', es: 'ES tw' }] }],
      facebook: [{ text: [{ de: 'DE fb', en: 'EN fb', es: 'ES fb' }] }],
      instagram: [{ text: [{ de: 'DE ig', en: 'EN ig', es: 'ES ig' }] }],
    },
    id: 'post-1',
  };
}

describe('PhotoPostWizard presenter - posting flows', () => {
  it('generate -> immediate post calls onPublishSocialPost', async () => {
    const user = userEvent.setup();

    const onGenerateSocialPosts = vi.fn().mockResolvedValue(makeOutput());
    const onPublishSocialPost = vi.fn().mockResolvedValue({ status: 'sucess' });

    render(
      <PhotoPostWizard
        eventId={'e1'}
        onComplete={() => {}}
        images={[{ id: 'img-prop-1', url: 'https://example.com/img.jpg' }]}
        onGenerateSocialPosts={onGenerateSocialPosts}
        onPublishSocialPost={onPublishSocialPost}
      />
    );

    // Select image via the select hotspot (absolute control)
    const hotspot = document.querySelector('div.absolute.top-1.right-1') as HTMLElement | null;
    if (hotspot) {
      await user.click(hotspot);
    }

    // Type description
    const desc = screen.getByPlaceholderText(/Was passiert auf dem Foto/i);
    await user.type(desc, 'Beschreibung');

    // Generate
    const genBtn = screen.getByRole('button', { name: /Vorschläge generieren/i });
    await user.click(genBtn);

    // Review should be visible now, then immediate post
    await screen.findAllByRole('textbox');
    const immediateBtn = screen.getByRole('button', { name: /Sofort senden/i });
    await user.click(immediateBtn);

    expect(onPublishSocialPost).toHaveBeenCalledTimes(1);
    const callArgs = onPublishSocialPost.mock.calls[0][0];
    expect(callArgs).toHaveProperty('postId');
  });

  it('generate -> scheduled post with datetime', async () => {
    const user = userEvent.setup();

    const onGenerateSocialPosts = vi.fn().mockResolvedValue(makeOutput());
    const onPublishSocialPost = vi.fn().mockResolvedValue({ status: 'sucess' });

    render(
      <PhotoPostWizard
        eventId={'e1'}
        onComplete={() => {}}
        images={[{ id: 'img-prop-2', url: 'https://example.com/img.jpg' }]}
        onGenerateSocialPosts={onGenerateSocialPosts}
        onPublishSocialPost={onPublishSocialPost}
      />
    );

    // Select image via hotspot
    const hotspot2 = document.querySelector('div.absolute.top-1.right-1') as HTMLElement | null;
    if (hotspot2) {
      await user.click(hotspot2);
    }
    const desc = screen.getByPlaceholderText(/Was passiert auf dem Foto/i);
    await user.type(desc, 'Beschreibung');

    // Generate
    const genBtn = screen.getByRole('button', { name: /Vorschläge generieren/i });
    await user.click(genBtn);

    // Ensure review is visible, then set datetime and click "Später posten"
    await screen.findAllByRole('textbox');
    const dtInput = document.querySelector('input[type="datetime-local"]') as HTMLInputElement | null;
    const value = '2025-01-01T10:00';
    if (dtInput) {
      fireEvent.change(dtInput, { target: { value } });
    }

    const scheduleBtn = await screen.findByRole('button', { name: /Später posten/i });
    await user.click(scheduleBtn);

    expect(onPublishSocialPost).toHaveBeenCalledTimes(1);
    const call = onPublishSocialPost.mock.calls[0][0];
    expect(call.scheduledTime).toBe(value);
  });
});
