import { describe, test, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { ChatToolTrace } from './chat-tool-trace'
import type { ChatToolItem } from '../types'

describe('ChatToolTrace', () => {
  const completeTool: ChatToolItem = {
    id: '1',
    name: 'add_marker',
    status: 'complete',
    reference: 'add_marker',
    duration: 1.8,
    inputArguments:
      '{"latitude": 39.610861,\n"label": "Calle Toledo 1, Ciudad Real",\n"longitude": -4.2393630}',
    output: '{ "success": true, "data": {} }',
  }

  const runningTool: ChatToolItem = {
    id: '2',
    name: 'execute_sql',
    status: 'running',
  }

  const errorTool: ChatToolItem = {
    id: '3',
    name: 'execute_sql',
    status: 'error',
    reference: 'execute_sql',
    duration: 1.8,
    inputArguments: '{"datasetId": "abc123"}',
    output: 'HTTP 400: Bad Request\n{"status":400,"error":"Syntax error"}',
  }

  test('renders "Tool executed" label for completed tools', () => {
    render(<ChatToolTrace tool={completeTool} />)
    expect(screen.getByText('Tool executed')).toBeTruthy()
  })

  test('renders reference name when provided', () => {
    render(<ChatToolTrace tool={completeTool} expanded />)
    expect(screen.getByText('add_marker')).toBeTruthy()
  })

  test('renders duration when provided', () => {
    render(<ChatToolTrace tool={completeTool} expanded />)
    expect(screen.getByText('1.8s')).toBeTruthy()
  })

  test('renders Success status for completed tools', () => {
    render(<ChatToolTrace tool={completeTool} expanded />)
    expect(screen.getByText('Success')).toBeTruthy()
  })

  test('renders Error status for failed tools', () => {
    render(<ChatToolTrace tool={errorTool} expanded />)
    expect(screen.getByText('Error')).toBeTruthy()
  })

  test('is NOT expandable when status is running', () => {
    const { container } = render(<ChatToolTrace tool={runningTool} />)
    expect(container.querySelector('button')).toBeNull()
  })

  test('renders input arguments code area', () => {
    render(<ChatToolTrace tool={completeTool} expanded />)
    expect(screen.getByText(/latitude/)).toBeTruthy()
  })

  test('renders output code area', () => {
    render(<ChatToolTrace tool={completeTool} expanded />)
    expect(screen.getByText(/success/)).toBeTruthy()
  })

  test('calls onExpandedChange callback', () => {
    const onChange = vi.fn()
    render(<ChatToolTrace tool={completeTool} onExpandedChange={onChange} />)
    const summary = screen.getByText('Tool executed').closest('button')
    if (summary) fireEvent.click(summary)
    expect(onChange).toHaveBeenCalled()
  })
})
