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

import BatchShow from './Show';

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
      <a href={href}>{children}</a>
    ),
    router: { post: vi.fn() },
    usePage: () => ({
      props: { polling_interval_ms: 3000 },
    }),
  };
});

vi.mock('@/Layouts/DashboardLayout', () => ({
  default: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="dashboard-layout">{children}</div>
  ),
}));

vi.mock('@/Components/Navigation/SiteNav', () => ({
  default: () => <div data-testid="site-nav" />,
}));

vi.mock('@/Components/ui/badge', () => ({
  Badge: ({ children, variant }: { children: React.ReactNode; variant?: string }) => (
    <span data-testid="badge" data-variant={variant}>{children}</span>
  ),
}));

vi.mock('@/Components/ui/button', () => ({
  Button: ({
    children,
    onClick,
    disabled,
  }: {
    children: React.ReactNode;
    onClick?: () => void;
    disabled?: boolean;
  }) => (
    <button onClick={onClick} disabled={disabled}>
      {children}
    </button>
  ),
}));

vi.mock('@/Components/ui/card', () => ({
  Card: ({ children }: { children: React.ReactNode }) => <div data-testid="card">{children}</div>,
  CardContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CardHeader: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CardTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('@/Components/ui/empty-state', () => ({
  EmptyState: ({ title }: { title: string }) => <div data-testid="empty-state">{title}</div>,
}));

vi.mock('@/hooks/usePolling', () => ({
  usePolling: vi.fn(),
}));

vi.mock('@/lib/format', () => ({
  formatNumber: (n: number) => String(n),
  formatDateTime: (d: string) => d,
}));

vi.mock('sonner', () => ({
  toast: { success: vi.fn(), error: vi.fn() },
}));

const mockBatchJob = {
  id: 1,
  status: 'completed' as const,
  total_jobs: 5,
  completed_jobs: 4,
  failed_jobs: 1,
  pending_jobs: 0,
  progress_percent: 80,
  total_estimated_tokens: 10000,
  total_estimated_cost: 0.5,
  total_actual_tokens: 9000,
  total_actual_cost: 0.45,
  settings_snapshot: { model: 'gpt-4o-mini' },
  started_at: '2026-01-15T10:00:00Z',
  completed_at: '2026-01-15T10:05:00Z',
  created_at: '2026-01-15T09:59:00Z',
};

const mockAiJob = {
  id: 1,
  status: 'completed' as const,
  total_recommendations: 2,
  completed_recommendations: 2,
  error: null,
  total_prompt_tokens: 500,
  total_completion_tokens: 300,
  created_at: '2026-01-15T10:00:00Z',
  completed_at: '2026-01-15T10:01:00Z',
  drafts: [
    {
      id: 1,
      recommendation: {
        id: 1,
        page_url: '/article-1',
        title: 'Article 1',
        action_type: 'content_rewrite',
      },
    },
  ],
};

const mockProps = {
  site: { id: 1, name: 'Test Site', domain: 'https://test.com' },
  batchJob: mockBatchJob,
  aiJobs: [mockAiJob],
};

describe('Batch/Show', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.stubGlobal('route', vi.fn((...args: string[]) => `/mock-route/${args[0]}`));
  });

  it('renders SiteNav', () => {
    render(<BatchShow {...mockProps} />);
    expect(screen.getByTestId('site-nav')).toBeInTheDocument();
  });

  it('displays completed status badge', () => {
    render(<BatchShow {...mockProps} />);
    const badges = screen.getAllByTestId('badge');
    const completedBadge = badges.find((b) => b.textContent === 'completed');
    expect(completedBadge).toBeInTheDocument();
  });

  it('shows AI jobs list', () => {
    render(<BatchShow {...mockProps} />);
    // Job info should be rendered
    expect(screen.getAllByTestId('card').length).toBeGreaterThan(0);
  });

  it('assigns DashboardLayout as layout', () => {
    expect(BatchShow.layout).toBeDefined();
  });

  it('shows empty state when no AI jobs', () => {
    render(<BatchShow {...mockProps} aiJobs={[]} />);
    expect(screen.getByTestId('empty-state')).toBeInTheDocument();
  });
});
