import React from 'react';
import { describe, it, expect } 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, fireEvent, within } from '@testing-library/react';
import BookmarksPage from '@/pages/Bookmarks/Bookmarks';
import { BlogIndividualPost } from '@/pages/BlogIndividualPost/BlogIndividualPost';
import { http, HttpResponse } from 'msw';
import { server } from '../msw/server';

describe('Bookmarks', () => {
  it('saves a post bookmark and shows it in the list', async () => {
    server.use(
      http.get('/arbitrary/BLOG/:user/:blog', ({ params }) =>
        HttpResponse.json({ title: 'My Blog', blogId: params.blog }),
      ),
      http.get('/arbitrary/BLOG_POST/:user/:fullId', ({ params }) => {
        const { fullId, user } = params as any;
        if (typeof fullId === 'string' && fullId.includes('-post-') && user) {
          return HttpResponse.json({
            title: 'Bookmark Me',
            createdAt: 1,
            postContent: [{ type: 'editor', id: 'e1', version: 1, content: [{ text: 'Body' }] }],
          });
        }
        return HttpResponse.json({}, { status: 404 });
      }),
      http.get('/arbitrary/resources/search', () => HttpResponse.json([])),
    );

    render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter initialEntries={[`/alice/myblog/123`]}>
            <Routes>
              <Route path="/:user/:blog/:postId" element={<BlogIndividualPost />} />
              <Route path="/bookmarks" element={<BookmarksPage />} />
            </Routes>
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );

    // Wait for post title
    expect(await screen.findByText('Bookmark Me')).toBeInTheDocument();
    // Click save to bookmarks
    const saveBtn = await screen.findByLabelText('Save to bookmarks');
    fireEvent.click(saveBtn);
    // Navigate to bookmarks within the same router and verify
    const { container } = render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter initialEntries={[`/bookmarks`]}>
            <Routes>
              <Route path="/bookmarks" element={<BookmarksPage />} />
            </Routes>
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );
    // Assert within the Bookmarks render only
    expect(within(container).getByText('Bookmarks')).toBeInTheDocument();
    expect(within(container).getByText('Bookmark Me')).toBeInTheDocument();
  });
});
