import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import ItemPage from '../src/pages/ItemPage.js'
import type { Item } from '../src/types.js'

vi.mock('../src/api.js', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../src/api.js')>()
  return {
    ...actual,
    api: { ...actual.api, getItem: vi.fn(), setRip: vi.fn(), setMatch: vi.fn(), deleteItem: vi.fn(), searchAlbums: vi.fn() },
  }
})

import { api } from '../src/api.js'

const item: Item = {
  id: 1,
  discogsReleaseId: 1001,
  title: 'Motion',
  artist: 'The Cinematic Orchestra',
  year: 1999,
  formats: ['CD'],
  genres: ['Electronic'],
  labels: ['Ninja Tune'],
  tracklist: [{ position: '1', title: 'Overture' }],
  catno: 'ZENCD012',
  country: 'UK',
  artworkUrl: '/artwork/abc.jpg',
  barcodes: ['5021592210629'],
  dateAdded: '2026-08-29',
  ripOverride: null,
  ripStatus: 'not_ripped',
}

beforeEach(() => {
  vi.mocked(api.getItem).mockReset()
  vi.mocked(api.getItem).mockResolvedValue(item as never)
  vi.mocked(api.setRip).mockReset()
  vi.mocked(api.setMatch).mockReset()
  vi.mocked(api.deleteItem).mockReset()
  vi.mocked(api.searchAlbums).mockReset()
})

function renderItem() {
  return render(
    <MemoryRouter initialEntries={['/item/1']}>
      <Routes>
        <Route path="/item/:id" element={<ItemPage />} />
        <Route path="/library" element={<p>library</p>} />
      </Routes>
    </MemoryRouter>
  )
}

describe('ItemPage', () => {
  it('renders metadata and the rip-status banner', async () => {
    renderItem()
    await waitFor(() => expect(screen.getByRole('heading', { name: 'Motion' })).toBeTruthy())
    expect(screen.getByText('The Cinematic Orchestra')).toBeTruthy()
    expect(screen.getByText(/not ripped yet/i)).toBeTruthy()
    expect(screen.getByText(/ZENCD012/)).toBeTruthy()
    expect(screen.getByText(/5021592210629/)).toBeTruthy()
    expect(screen.getByText('Overture')).toBeTruthy()
    expect(screen.getByRole('link', { name: /view on discogs/i }).getAttribute('href')).toBe(
      'https://www.discogs.com/release/1001'
    )
  })

  it('rip override: mark ripped, then reset to auto', async () => {
    vi.mocked(api.setRip).mockResolvedValue({ ...item, ripOverride: true, ripStatus: 'ripped' } as never)
    renderItem()
    await userEvent.click(await screen.findByRole('button', { name: /mark ripped/i }))
    await waitFor(() => expect(api.setRip).toHaveBeenCalledWith(1, true))
    await waitFor(() => expect(screen.getByText(/in your digital collection/i)).toBeTruthy())

    vi.mocked(api.setRip).mockResolvedValue(item as never)
    await userEvent.click(screen.getByRole('button', { name: /reset to auto/i }))
    await waitFor(() => expect(api.setRip).toHaveBeenCalledWith(1, null))
  })

  it('re-match: search albums and link one', async () => {
    vi.mocked(api.searchAlbums).mockResolvedValue({
      albums: [{ id: 77, subsonicId: 'a1', title: 'Motion (Remaster)', artist: 'The Cinematic Orchestra' }],
    } as never)
    vi.mocked(api.setMatch).mockResolvedValue({ ...item, ripStatus: 'ripped' } as never)
    renderItem()
    await userEvent.click(await screen.findByRole('button', { name: /re-match/i }))
    await userEvent.click(screen.getByRole('button', { name: /^search$/i }))
    const albumRadio = await screen.findByRole('radio', { name: /motion \(remaster\)/i })
    await userEvent.click(albumRadio)
    await userEvent.click(screen.getByRole('button', { name: /^link$/i }))
    await waitFor(() => expect(api.setMatch).toHaveBeenCalledWith(1, 77))
  })

  it('unlink clears the match', async () => {
    vi.mocked(api.setMatch).mockResolvedValue(item as never)
    renderItem()
    await userEvent.click(await screen.findByRole('button', { name: /re-match/i }))
    await userEvent.click(screen.getByRole('button', { name: /^unlink$/i }))
    await waitFor(() => expect(api.setMatch).toHaveBeenCalledWith(1, null))
  })

  it('remove deletes the item and navigates back to the library', async () => {
    vi.mocked(api.deleteItem).mockResolvedValue({ ok: true } as never)
    renderItem()
    await userEvent.click(await screen.findByRole('button', { name: /^remove$/i }))
    await userEvent.click(await screen.findByRole('button', { name: /^confirm remove$/i }))
    await waitFor(() => expect(api.deleteItem).toHaveBeenCalledWith(1))
    await waitFor(() => expect(screen.getByText('library')).toBeTruthy())
  })

  it('re-match clears the picked album when searching again', async () => {
    vi.mocked(api.searchAlbums)
      .mockResolvedValueOnce({
        albums: [{ id: 77, subsonicId: 'a1', title: 'Motion (Remaster)', artist: 'The Cinematic Orchestra' }],
      } as never)
      .mockResolvedValueOnce({
        albums: [{ id: 88, subsonicId: 'a2', title: 'Something Else', artist: 'Other Artist' }],
      } as never)
    renderItem()
    await userEvent.click(await screen.findByRole('button', { name: /re-match/i }))
    await userEvent.click(screen.getByRole('button', { name: /^search$/i }))
    await userEvent.click(await screen.findByRole('radio', { name: /motion \(remaster\)/i }))
    await userEvent.click(screen.getByRole('button', { name: /^search$/i }))
    const linkBtn = await screen.findByRole('button', { name: /^link$/i })
    expect(linkBtn).toHaveProperty('disabled', true)
  })
})
