import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { Provider } from 'react-redux';
import { store } from '@/state/store';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { render, screen, waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { server } from '../msw/server';
import { CreatePost } from '@/pages/CreatePost/CreatePost';

// Ensure global qortalRequest exists and is mockable
describe('CreatePost (edit) — wiki publish without currentBlog', () => {
  it('publishes BLOG_POST even when currentBlog is null', async () => {
    // Mock QDN endpoints for settings and content
    server.use(
      // Find BLOG owner by identifier
      http.get('/arbitrary/resources', ({ request }) => {
        const url = new URL(request.url);
        if (
          url.searchParams.get('service') === 'BLOG' &&
          url.searchParams.get('identifier') === 'q-blog-myblog'
        ) {
          return HttpResponse.json([{ name: 'owner', identifier: 'q-blog-myblog' }]);
        }
        return HttpResponse.json([]);
      }),
      // Blog JSON with wiki enabled, global allow
      http.get('/arbitrary/BLOG/:name/:id', ({ params }) => {
        const { name, id } = params as any;
        if (name === 'owner' && id === 'q-blog-myblog') {
          return HttpResponse.json({
            title: 'Owner Blog',
            wikiEnabled: true,
            editorWhitelist: [],
            editorBlacklist: [],
          });
        }
        return HttpResponse.json({});
      }),
      // Revisions search
      http.get('/arbitrary/resources/search', ({ request }) => {
        const url = new URL(request.url);
        if (
          url.searchParams.get('service') === 'BLOG_POST' &&
          url.searchParams.get('identifier') === 'q-blog-myblog-post-123'
        ) {
          return HttpResponse.json([
            { name: 'owner', identifier: 'q-blog-myblog-post-123', updated: 1000 },
          ]);
        }
        return HttpResponse.json([]);
      }),
      // Load existing canonical content (simplified)
      http.get('/arbitrary/BLOG_POST/:name/:fullId', ({ params }) => {
        const { name, fullId } = params as any;
        if (fullId === 'q-blog-myblog-post-123') {
          return HttpResponse.json({
            title: 'Original Title',
            postContent: [],
            layouts: [],
            layoutGeneralSettings: { blogPostType: 'minimal' },
          });
        }
        return HttpResponse.json({});
      }),
    );

    // Mock authenticated user with a different Name and NO currentBlog
    // GlobalWrapper's askForAccountInformation isn't used here; we set store auth directly
    (globalThis as any).qortalRequest = vi.fn().mockResolvedValue({ ok: true });

    store.dispatch({
      type: 'auth/addUser',
      payload: { address: 'QADDRX', publicKey: 'PUB', name: 'alice' },
    });
    render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter initialEntries={[`/alice/myblog/123/edit`]}>
            <Routes>
              <Route path="/:user/:blog/:postId/edit" element={<CreatePost mode="edit" />} />
            </Routes>
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );

    // Wait for editor to show Publish; open the modal
    const publishBtn = await screen.findByRole('button', { name: /Publish/i });
    publishBtn.click();

    // Title should appear in the modal
    const titleInput = await screen.findByDisplayValue('Original Title');
    expect(titleInput).toBeInTheDocument();

    // Confirm publish in the modal
    const submitBtn = await screen.findByRole('button', { name: /Submit/i });
    submitBtn.click();

    await waitFor(() => {
      expect(globalThis.qortalRequest).toHaveBeenCalled();
    });

    const call = (globalThis.qortalRequest as any).mock.calls.find(
      (c: any[]) => c[0]?.action === 'PUBLISH_QDN_RESOURCE',
    );
    expect(call).toBeTruthy();
    expect(call[0]).toMatchObject({
      service: 'BLOG_POST',
      identifier: 'q-blog-myblog-post-123',
      name: 'alice',
    });
  });
});
