import { fireEvent, screen, waitFor } from '@testing-library/react'
import { Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'

import WikiEditPage from '@/pages/wiki/WikiEditPage'
import { buildUser, buildWikiPage } from '@/test/factories'
import { renderWithProviders } from '@/test/render'

const api = vi.hoisted (() => ({
  apiGet: vi.fn (),
  apiPut: vi.fn (),
}))

const toastApi = vi.hoisted (() => ({
  toast: vi.fn (),
}))

vi.mock ('@/lib/api', () => api)
vi.mock ('@/components/ui/use-toast', () => toastApi)
vi.mock ('react-markdown-editor-lite', () => ({
  default: ({ value, onChange }: {
    value:    string
    onChange: (event: { text: string }) => void
  }) => (
      <textarea
          aria-label="本文エディタ"
          value={value}
          onChange={ev => onChange ({ text: ev.target.value })}/>
  ),
}))

const renderPage = (user = buildUser ({ role: 'member' })) =>
  renderWithProviders (
      <Routes>
        <Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
      </Routes>,
      { route: '/wiki/9/edit' },
  )

describe ('WikiEditPage', () => {
  it ('blocks guests', () => {
    renderPage (buildUser ({ role: 'guest' }))

    expect (screen.getByText ('403')).toBeInTheDocument ()
  })

  it ('loads the target page for editing', async () => {
    api.apiGet.mockResolvedValueOnce (buildWikiPage ({ title: '既存', body: '本文' }))

    renderPage ()

    await waitFor (() => {
      expect (api.apiGet).toHaveBeenCalledWith ('/wiki/9')
    })
    expect (screen.getAllByRole ('textbox')[0]).toHaveValue ('既存')
    expect (screen.getByLabelText ('本文エディタ')).toHaveValue ('本文')
  })

  it ('submits edited title and body', async () => {
    api.apiGet.mockResolvedValueOnce (buildWikiPage ({ title: '既存', body: '本文' }))
    api.apiPut.mockResolvedValueOnce ({})

    renderPage ()

    const title = await screen.findByDisplayValue ('既存')
    fireEvent.change (title, { target: { value: '更新済み' } })
    fireEvent.change (screen.getByLabelText ('本文エディタ'), { target: { value: '更新本文' } })
    fireEvent.click (screen.getByRole ('button', { name: '編輯' }))

    await waitFor (() => {
      expect (api.apiPut).toHaveBeenCalledWith (
          '/wiki/9',
          expect.any (FormData),
          { headers: { 'Content-Type': 'multipart/form-data' } },
      )
    })
    const formData = api.apiPut.mock.calls[0]?.[1] as FormData
    expect (formData.get ('title')).toBe ('更新済み')
    expect (formData.get ('body')).toBe ('更新本文')
    expect (toastApi.toast).toHaveBeenCalledWith ({ title: '投稿成功!' })
  })
})
