import type { ReactNode } from 'react'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { OperationLog, OperationLogListParams, OperationLogListResponse } from '@/types/operation-log'
import { OperationLogsPage } from './OperationLogsPage'

const listOperationLogsMock = vi.fn<(params?: OperationLogListParams) => Promise<OperationLogListResponse>>()

vi.mock('antd', async () => {
  const React = await import('react')

  function resolveRowKey<RecordType extends Record<string, unknown>>(
    record: RecordType,
    rowKey: string | ((row: RecordType) => string | number) | undefined,
    index: number,
  ): string {
    if (typeof rowKey === 'function') {
      return String(rowKey(record))
    }
    if (typeof rowKey === 'string') {
      return String(record[rowKey] ?? index)
    }
    return String(index)
  }

  function flattenChildren(children: ReactNode): string {
    if (typeof children === 'string' || typeof children === 'number') {
      return String(children)
    }
    if (Array.isArray(children)) {
      return children.map(flattenChildren).join(' ').trim()
    }
    return ''
  }

  const RangePicker = ({
    placeholder = ['start', 'end'],
    onChange,
  }: {
    placeholder?: [string, string]
    onChange?: (dates: null, dateStrings: [string, string]) => void
  }) => {
    const [start, setStart] = React.useState('')
    const [end, setEnd] = React.useState('')

    return (
      <div>
        <input
          aria-label={placeholder[0]}
          value={start}
          onChange={(event) => {
            const nextStart = event.target.value
            setStart(nextStart)
            onChange?.(null, [nextStart, end])
          }}
        />
        <input
          aria-label={placeholder[1]}
          value={end}
          onChange={(event) => {
            const nextEnd = event.target.value
            setEnd(nextEnd)
            onChange?.(null, [start, nextEnd])
          }}
        />
      </div>
    )
  }

  return {
    Button: ({
      children,
      onClick,
      htmlType,
      type: buttonType,
      icon,
      ...props
    }: {
      children?: ReactNode
      onClick?: () => void
      htmlType?: 'button' | 'submit' | 'reset'
      [key: string]: unknown
    }) => {
      void buttonType
      void icon

      return (
        <button type={htmlType ?? 'button'} onClick={onClick} {...props}>
          {children}
        </button>
      )
    },
    DatePicker: { RangePicker },
    Input: ({
      onPressEnter,
      prefix,
      allowClear,
      ...props
    }: {
      onPressEnter?: () => void
      prefix?: ReactNode
      allowClear?: boolean
      [key: string]: unknown
    }) => {
      void prefix
      void allowClear

      return (
        <input
          {...props}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              onPressEnter?.()
            }
          }}
        />
      )
    },
    Select: ({
      value,
      onChange,
      options = [],
      placeholder,
      allowClear,
      ...props
    }: {
      value?: string | number
      onChange?: (value: unknown) => void
      options?: Array<{ value: string | number, label: ReactNode }>
      placeholder?: string
      allowClear?: boolean
      [key: string]: unknown
    }) => {
      void allowClear

      return (
        <select
          aria-label={placeholder ?? 'select'}
          value={value === undefined ? '' : String(value)}
          onChange={(event) => {
            const nextValue = event.target.value
            if (nextValue === '') {
              onChange?.(undefined)
              return
            }

            const matchedOption = options.find((option) => String(option.value) === nextValue)
            onChange?.(matchedOption?.value ?? nextValue)
          }}
          {...props}
        >
          <option value="">{placeholder ?? 'all'}</option>
          {options.map((option) => (
            <option key={String(option.value)} value={String(option.value)}>
              {flattenChildren(option.label)}
            </option>
          ))}
        </select>
      )
    },
    Space: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
    Table: ({
      columns,
      dataSource,
      rowKey,
      locale,
      pagination,
    }: {
      columns: Array<{
        key?: string
        title?: ReactNode
        dataIndex?: string
        render?: (value: unknown, record: Record<string, unknown>, index: number) => ReactNode
      }>
      dataSource?: Array<Record<string, unknown>>
      rowKey?: string | ((row: Record<string, unknown>) => string | number)
      locale?: { emptyText?: ReactNode }
      pagination?: {
        current?: number
        pageSize?: number
        total?: number
        onChange?: (page: number, pageSize: number) => void
      }
    }) => {
      const rows = dataSource ?? []

      if (rows.length === 0) {
        return <div>{locale?.emptyText ?? null}</div>
      }

      return (
        <div>
          <table>
            <thead>
              <tr>
                {columns.map((column, index) => (
                  <th key={column.key ?? column.dataIndex ?? index}>{column.title}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((record, rowIndex) => (
                <tr
                  key={resolveRowKey(record, rowKey, rowIndex)}
                  data-testid={`table-row-${resolveRowKey(record, rowKey, rowIndex)}`}
                >
                  {columns.map((column, columnIndex) => {
                    const value = column.dataIndex ? record[column.dataIndex] : undefined
                    const content = column.render ? column.render(value, record, rowIndex) : value
                    return (
                      <td key={column.key ?? column.dataIndex ?? columnIndex}>
                        {content as ReactNode}
                      </td>
                    )
                  })}
                </tr>
              ))}
            </tbody>
          </table>
          <button
            type="button"
            onClick={() => pagination?.onChange?.(1, 50)}
          >
            paginate
          </button>
          <span>{`${pagination?.current ?? 1}-${pagination?.pageSize ?? 20}-${pagination?.total ?? rows.length}`}</span>
        </div>
      )
    },
    Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
  }
})

vi.mock('@ant-design/icons', () => ({
  EyeOutlined: () => <span>eye</span>,
  ReloadOutlined: () => <span>reload</span>,
  SearchOutlined: () => <span>search</span>,
}))

vi.mock('@/components/common', () => ({
  PageHeader: ({
    title,
    description,
    actions,
  }: {
    title: ReactNode
    description?: ReactNode
    actions?: ReactNode
  }) => (
    <section data-testid="page-header">
      <h1>{title}</h1>
      <p>{description}</p>
      {actions}
    </section>
  ),
}))

vi.mock('@/components/feedback', () => ({
  PageEmpty: ({ description }: { description?: ReactNode }) => <div>{description ?? 'empty'}</div>,
  PageError: ({
    description,
    onRetry,
  }: {
    description?: ReactNode
    onRetry?: () => void
  }) => (
    <div>
      <p>{description}</p>
      <button type="button" onClick={onRetry}>retry</button>
    </div>
  ),
}))

vi.mock('@/components/layout', () => ({
  PageLayout: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
  FilterCard: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
  TableCard: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
}))

vi.mock('@/services/operation-logs', () => ({
  listOperationLogs: (params?: OperationLogListParams) => listOperationLogsMock(params),
}))

vi.mock('./OperationLogDetailDrawer', () => ({
  OperationLogDetailDrawer: ({
    open,
    log,
    onClose,
  }: {
    open: boolean
    log: OperationLog | null
    onClose: () => void
  }) => (
    open ? (
      <div data-testid="operation-log-detail-drawer">
        <span>{`detail:${log?.id ?? 'none'}`}</span>
        <button type="button" onClick={onClose}>close detail</button>
      </div>
    ) : null
  ),
}))

function buildLog(id: number, userId: number, requestMethod: string, operationName: string): OperationLog {
  return {
    id,
    user_id: userId,
    operation_type: 'user',
    operation_name: operationName,
    request_method: requestMethod,
    request_path: `/api/v1/logs/${id}`,
    request_params: `{"id":${id}}`,
    response_status: requestMethod === 'GET' ? 200 : 500,
    ip: `10.0.1.${id}`,
    user_agent: 'Chrome',
    created_at: `2026-03-27 1${id}:00:00`,
  }
}

describe('OperationLogsPage', () => {
  let currentLogs: OperationLog[]

  beforeEach(() => {
    currentLogs = [
      buildLog(1, 9, 'GET', 'fetch users'),
      buildLog(2, 9, 'POST', 'create user'),
      buildLog(3, 12, 'DELETE', 'delete user'),
    ]

    listOperationLogsMock.mockReset()
    listOperationLogsMock.mockImplementation(async (params?: OperationLogListParams) => {
      const page = params?.page ?? 1
      const pageSize = params?.page_size ?? 20

      let items = currentLogs

      if (params?.user_id !== undefined) {
        items = items.filter((log) => log.user_id === params.user_id)
      }

      if (params?.method) {
        items = items.filter((log) => log.request_method === params.method)
      }

      if (params?.keyword) {
        const keyword = params.keyword.toLowerCase()
        items = items.filter((log) => (
          log.operation_name.toLowerCase().includes(keyword) ||
          log.request_path.toLowerCase().includes(keyword)
        ))
      }

      const start = (page - 1) * pageSize
      const pagedItems = items.slice(start, start + pageSize)

      return {
        items: pagedItems.map((log) => ({ ...log })),
        total: items.length,
        page,
        page_size: pageSize,
      }
    })
  })

  afterEach(() => {
    vi.restoreAllMocks()
  })

  it('loads, filters, resets, paginates, refreshes, and opens detail drawer', async () => {
    const user = userEvent.setup()

    render(<OperationLogsPage />)

    expect(await screen.findByText('fetch users')).toBeInTheDocument()
    expect(screen.getByText('create user')).toBeInTheDocument()
    expect(listOperationLogsMock).toHaveBeenLastCalledWith(expect.objectContaining({
      page: 1,
      page_size: 20,
      user_id: undefined,
      method: undefined,
      keyword: undefined,
    }))

    const [refreshButton, searchButton, resetButton] = screen.getAllByRole('button').slice(0, 3)
    const [userIdInput, keywordInput] = screen.getAllByRole('textbox')
    const methodSelect = screen.getByRole('combobox')

    await user.type(userIdInput, '9')
    await user.selectOptions(methodSelect, 'POST')
    await user.type(keywordInput, 'create')
    await user.click(searchButton)

    await waitFor(() => expect(screen.queryByText('fetch users')).not.toBeInTheDocument())
    expect(screen.getByText('create user')).toBeInTheDocument()
    expect(listOperationLogsMock).toHaveBeenLastCalledWith(expect.objectContaining({
      user_id: 9,
      method: 'POST',
      keyword: 'create',
    }))

    await user.click(resetButton)

    await waitFor(() => expect(screen.getByText('fetch users')).toBeInTheDocument())
    expect(screen.getByText('delete user')).toBeInTheDocument()
    expect(listOperationLogsMock).toHaveBeenLastCalledWith(expect.objectContaining({
      user_id: undefined,
      method: undefined,
      keyword: undefined,
    }))

    const callCountBeforeRefresh = listOperationLogsMock.mock.calls.length
    await user.click(refreshButton)
    await waitFor(() => expect(listOperationLogsMock.mock.calls.length).toBeGreaterThan(callCountBeforeRefresh))

    await user.click(screen.getByRole('button', { name: 'paginate' }))
    await waitFor(() => expect(listOperationLogsMock).toHaveBeenLastCalledWith(expect.objectContaining({
      page: 1,
      page_size: 50,
    })))

    const firstRow = screen.getByTestId('table-row-1')
    await user.click(within(firstRow).getByRole('button'))
    expect(screen.getByTestId('operation-log-detail-drawer')).toHaveTextContent('detail:1')

    await user.click(screen.getByRole('button', { name: 'close detail' }))
    await waitFor(() => expect(screen.queryByTestId('operation-log-detail-drawer')).not.toBeInTheDocument())
  })

  it('renders the page error state and retries fetching', async () => {
    const user = userEvent.setup()

    listOperationLogsMock.mockReset()
    listOperationLogsMock.mockRejectedValueOnce(new Error('operation logs failed'))
    listOperationLogsMock.mockResolvedValue({
      items: currentLogs.map((log) => ({ ...log })),
      total: currentLogs.length,
      page: 1,
      page_size: 20,
    })

    render(<OperationLogsPage />)

    expect(await screen.findByText('operation logs failed')).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: 'retry' }))

    await waitFor(() => expect(screen.getByText('fetch users')).toBeInTheDocument())
    expect(listOperationLogsMock).toHaveBeenCalledTimes(2)
  })
})
