import { fireEvent, render, screen, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import RightsDashboard from './RightsDashboard'

const mocks = vi.hoisted(() => ({ getDashboard: vi.fn() }))
vi.mock('../api/client', async (importOriginal) => ({
  ...(await importOriginal<typeof import('../api/client')>()),
  getDashboard: mocks.getDashboard,
}))

const data = {
  summary: { applied: 2, docSubmitted: 0, reviewTotal: 120, reviewDone: 90, processTotal: 40, processDone: 10, unresolvedRe: 0, reportWriting: 0, completed: 0 },
  rights: { reviewResults: [{ label: '신유형개방', count: 90 }], reviewSourceKoglTypes: [{ label: '1유형', count: 120 }], reviewJudgedKoglTypes: [{ label: '1유형', count: 90 }], processTypes: [{ label: '0유형', count: 30 }, { label: '1유형', count: 10 }], processStatuses: [{ label: '진행중', count: 30 }, { label: '처리완료', count: 10 }], changedKoglCount: 6 },
  orgs: [
    { id: 1, orgNo: '001', orgName: '완료기관', stage: 7, hasChannel: true, lawyerName: null, mjName: null, lawyerAssignedDate: null, reviewTotal: 90, reviewDone: 90, processTotal: 10, processDone: 10, stageChangedAt: null, lastChangedAt: null, reCount: 0 },
    { id: 2, orgNo: '002', orgName: '대기기관', stage: 5, hasChannel: true, lawyerName: null, mjName: null, lawyerAssignedDate: null, reviewTotal: 30, reviewDone: 0, processTotal: 30, processDone: 0, stageChangedAt: null, lastChangedAt: null, reCount: 0 },
  ],
}

describe('RightsDashboard', () => {
  beforeEach(() => mocks.getDashboard.mockResolvedValue(data))

  it('DB 집계 응답으로 권리확인 현황을 표시한다', async () => {
    render(<RightsDashboard mode="review" onOpenOrg={() => {}} />)
    expect(await screen.findByText('90 / 120')).toBeTruthy()
    expect(screen.getAllByText('75%')).toHaveLength(3)
    expect(screen.getByText('완료기관')).toBeTruthy()
    expect(screen.getByText('권리확인 결과 유형별 현황')).toBeTruthy()
    expect(screen.getByText('검토 대상 분류 현황')).toBeTruthy()
    expect(screen.getByText('판정 공공누리유형 현황')).toBeTruthy()
  })

  it('기관 검색과 상태 필터가 동작한다', async () => {
    render(<RightsDashboard mode="process" onOpenOrg={() => {}} />)
    await screen.findByText('완료기관')
    expect(screen.getByText('유형변경 건수')).toBeTruthy()
    expect(screen.getByText('기존 유형과 최종 판정 유형이 다른 건')).toBeTruthy()
    fireEvent.change(screen.getByLabelText('기관명 검색'), { target: { value: '대기' } })
    expect(screen.queryByText('완료기관')).toBeNull()
    expect(screen.getByText('대기기관')).toBeTruthy()
    fireEvent.change(screen.getByLabelText('진행 상태'), { target: { value: 'complete' } })
    expect(screen.getByText('조건에 맞는 기관이 없습니다.')).toBeTruthy()
  })

  it('기관 행을 선택하면 상세 화면 콜백을 호출한다', async () => {
    const onOpenOrg = vi.fn()
    render(<RightsDashboard mode="review" onOpenOrg={onOpenOrg} />)
    const cell = await screen.findByText('완료기관')
    fireEvent.click(within(cell.closest('tr')!).getByText('완료기관'))
    expect(onOpenOrg).toHaveBeenCalledWith(1)
  })
})
