import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ClientContractItemEditPage } from '../ClientContractItemEditPage';

vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');
  return {
    ...actual,
    useNavigate: () => vi.fn(),
    useParams: () => ({ id: 'cli-1', itemId: 'item-1' }),
  };
});

vi.mock('../../../hooks/useClients', () => ({
  useClient: () => ({ data: { id: 'cli-1', name: 'Cliente A' } }),
}));
vi.mock('../../../hooks/useBreadcrumbs', () => ({
  useBreadcrumbs: () => [{ label: 'Dashboard', to: '/' }],
}));
vi.mock('../../../components/ui/Toast', () => ({
  useToast: () => ({ showToast: vi.fn() }),
}));
vi.mock('../../../hooks/usePageTitle', () => ({
  usePageTitle: () => ({ setPageTitle: vi.fn() }),
}));
vi.mock('../../../services/contract-items.service', () => ({
  updateContractItem: vi.fn(),
}));

const useContractItemMock = vi.fn();
vi.mock('../../../hooks/useContractItems', () => ({
  useContractItem: (...args: unknown[]) => useContractItemMock(...args),
}));

function renderPage() {
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={client}>
      <MemoryRouter>
        <ClientContractItemEditPage />
      </MemoryRouter>
    </QueryClientProvider>,
  );
}

describe('ClientContractItemEditPage', () => {
  it('mantém select de tipo desabilitado em modo edit', () => {
    useContractItemMock.mockReturnValue({
      data: {
        id: 'item-1',
        code: 'IC-1',
        name: 'Item',
        description: '',
        itemType: 'UST',
        totalUst: 1000,
        ustValue: 100,
        timeboxDescoberta: null,
        timeboxDesign: null,
        timeboxArquitetura: null,
        timeboxConstrucao: null,
      },
      isLoading: false,
    });

    const { container } = renderPage();

    const select = container.querySelector<HTMLSelectElement>('select[name="itemType"]')!;
    expect(select).toBeDisabled();
  });

  it('hidrata branch SAAS_LICENSE com Quantidade e Valor unitário sem timeboxes', () => {
    useContractItemMock.mockReturnValue({
      data: {
        id: 'item-1',
        code: 'IC-2',
        name: 'Licença',
        description: '',
        itemType: 'SAAS_LICENSE',
        totalUst: 50,
        ustValue: 200,
      },
      isLoading: false,
    });

    renderPage();

    expect(screen.getByText('Quantidade')).toBeInTheDocument();
    expect(screen.getByText('Valor unitário (R$)')).toBeInTheDocument();
    expect(screen.queryByText('Descoberta (h/semana)')).not.toBeInTheDocument();
  });
});
