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

vi.mock('@/Components/theme/use-theme', () => ({
  useTheme: vi.fn(() => ({ theme: 'system', setTheme: vi.fn(), resolvedTheme: 'light' })),
}));

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    router: {
      post: vi.fn(),
      get: vi.fn(),
      on: vi.fn(() => vi.fn()),
    },
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
      <a href={href}>{children}</a>
    ),
    usePage: vi.fn(() => ({
      url: '/admin/cannibalization-runs',
      props: {
        auth: { user: { id: 1, name: 'Admin', email: 'admin@test.com', is_admin: true }, impersonating: false },
        features: { billing: false, socialAuth: false, emailVerification: false, apiTokens: false, userSettings: false, notifications: false, onboarding: false, apiDocs: false, twoFactor: false, webhooks: false, admin: true },
        flash: {}, errors: {}, notifications_unread_count: 0, sites: [], limits: null, active_jobs: [], ai_max_batch_size: 10, ai_defaults: {}, polling_interval_ms: 5000, admin_failed_job_count: 0,
      },
    })),
  };
});

import { router } from '@inertiajs/react';

import AdminCannibalizationRunsIndex from './Index';

const makeRun = (overrides = {}) => ({
  id: 1,
  site_id: 10,
  site_name: 'Test Site',
  site_domain: 'test.com',
  status: 'failed',
  cases_count: 0,
  error: 'Timeout',
  started_at: null,
  completed_at: null,
  created_at: '2026-06-01T00:00:00Z',
  ...overrides,
});

const makeProps = (overrides = {}) => ({
  runs: {
    data: [makeRun()],
    current_page: 1,
    last_page: 1,
    per_page: 15,
    total: 1,
    from: 1,
    to: 1,
    links: [],
    path: '/admin/cannibalization-runs',
    first_page_url: '',
    last_page_url: '',
    next_page_url: null,
    prev_page_url: null,
  },
  filters: {},
  statuses: ['pending', 'processing', 'completed', 'failed', 'cancelled'],
  ...overrides,
});

describe('CannibalizationRuns/Index', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shows Retry button for failed runs', () => {
    render(<AdminCannibalizationRunsIndex {...makeProps()} />);
    expect(screen.getByRole('button', { name: /retry cannibalization run #1/i })).toBeInTheDocument();
  });

  it('does not fire router.post immediately on Retry click — opens dialog first', async () => {
    const user = userEvent.setup();
    render(<AdminCannibalizationRunsIndex {...makeProps()} />);
    await user.click(screen.getByRole('button', { name: /retry cannibalization run #1/i }));
    expect(router.post).not.toHaveBeenCalled();
    expect(screen.getByRole('alertdialog')).toBeInTheDocument();
    expect(screen.getByText(/re-dispatches the cannibalization detection job/i)).toBeInTheDocument();
  });

  it('fires router.post when confirm is clicked', async () => {
    const user = userEvent.setup();
    render(<AdminCannibalizationRunsIndex {...makeProps()} />);
    await user.click(screen.getByRole('button', { name: /retry cannibalization run #1/i }));
    await user.click(screen.getByRole('button', { name: /retry run/i }));
    expect(router.post).toHaveBeenCalledTimes(1);
  });

  it('does not fire router.post when cancel is clicked', async () => {
    const user = userEvent.setup();
    render(<AdminCannibalizationRunsIndex {...makeProps()} />);
    await user.click(screen.getByRole('button', { name: /retry cannibalization run #1/i }));
    await user.click(screen.getByRole('button', { name: /cancel/i }));
    expect(router.post).not.toHaveBeenCalled();
  });
});
