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

import TrafficAlertsIndex from './Index';

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: {
      visit: vi.fn(),
      reload: vi.fn(),
      get: vi.fn(),
      on: vi.fn(() => vi.fn()),
    },
    usePage: () => ({
      props: {},
    }),
  };
});

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/empty-state', () => ({
  EmptyState: ({ title, description }: { title: string; description: string }) => (
    <div data-testid="empty-state">
      <h2>{title}</h2>
      <p>{description}</p>
    </div>
  ),
}));

const mockSite = {
  id: 1,
  name: 'Test Site',
  domain: 'example.com',
};

const emptyFilters = {
  severity: null,
  status: null,
  anomaly_type: null,
  start_date: null,
  end_date: null,
  sort_by: null,
};

const zeroCounts = {
  total: 0,
  unacknowledged: 0,
  acknowledged: 0,
  dismissed: 0,
  critical: 0,
  warning: 0,
  info: 0,
};

const emptyAlerts = {
  data: [],
  links: [] as Array<{ url: string | null; label: string; active: boolean }>,
  current_page: 1,
  last_page: 1,
};

const mockAlert = {
  id: 1,
  site_id: 1,
  severity: 'warning' as const,
  anomaly_type: 'sudden_drop' as const,
  status: 'unacknowledged' as const,
  page_url: 'https://example.com/blog/test',
  metrics: {
    clicks_before: 500,
    clicks_after: 250,
    delta_percent: -50.0,
    impressions_before: 5000,
    impressions_after: 3000,
    ctr_before: 0.1,
    ctr_after: 0.083,
    position_before: 5.0,
    position_after: 8.0,
  },
  created_at: '2026-03-10T12:00:00Z',
  acknowledged_at: null,
  dismissed_at: null,
  finding_id: 1,
  analysis_run_id: 1,
};

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

  describe('rendering', () => {
    it('renders page heading "Traffic Alerts"', () => {
      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={emptyAlerts}
          filters={emptyFilters}
          counts={zeroCounts}
        />,
      );

      const headings = screen.getAllByRole('heading', { name: /traffic alerts/i });
      expect(headings.length).toBeGreaterThanOrEqual(1);
    });

    it('renders SiteNav component', () => {
      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={emptyAlerts}
          filters={emptyFilters}
          counts={zeroCounts}
        />,
      );

      expect(screen.getByTestId('site-nav')).toBeInTheDocument();
    });

    it('has layout property defined', () => {
      expect(TrafficAlertsIndex.layout).toBeDefined();
    });
  });

  describe('empty state', () => {
    it('shows empty state when no alerts exist', () => {
      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={emptyAlerts}
          filters={emptyFilters}
          counts={zeroCounts}
        />,
      );

      expect(screen.getByText('No traffic alerts')).toBeInTheDocument();
    });
  });

  describe('with data', () => {
    it('renders alert cards when alerts exist', () => {
      const alertsWithData = {
        data: [mockAlert],
        links: [] as Array<{ url: string | null; label: string; active: boolean }>,
        current_page: 1,
        last_page: 1,
      };

      const countsWithData = {
        total: 1,
        unacknowledged: 1,
        acknowledged: 0,
        dismissed: 0,
        critical: 0,
        warning: 1,
        info: 0,
      };

      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={alertsWithData}
          filters={emptyFilters}
          counts={countsWithData}
        />,
      );

      // Should show the alert page path (truncateUrl strips scheme+host, returns path only)
      expect(screen.getByText(/\/blog\/test/)).toBeInTheDocument();
    });

    it('renders severity badge for alerts', () => {
      const alertsWithData = {
        data: [mockAlert],
        links: [] as Array<{ url: string | null; label: string; active: boolean }>,
        current_page: 1,
        last_page: 1,
      };

      const countsWithData = {
        total: 1,
        unacknowledged: 1,
        acknowledged: 0,
        dismissed: 0,
        critical: 0,
        warning: 1,
        info: 0,
      };

      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={alertsWithData}
          filters={emptyFilters}
          counts={countsWithData}
        />,
      );

      // Should display the severity badge text (multiple "Warning" elements: stat card + alert badge)
      const warningElements = screen.getAllByText('Warning');
      expect(warningElements.length).toBeGreaterThanOrEqual(2);
    });

    it('shows stat cards with correct counts', () => {
      const countsWithData = {
        total: 5,
        unacknowledged: 3,
        acknowledged: 1,
        dismissed: 1,
        critical: 1,
        warning: 2,
        info: 2,
      };

      render(
        <TrafficAlertsIndex
          site={mockSite}
          alerts={emptyAlerts}
          filters={emptyFilters}
          counts={countsWithData}
        />,
      );

      // Total card
      expect(screen.getByText('Total')).toBeInTheDocument();
      expect(screen.getByText('Unacknowledged')).toBeInTheDocument();
    });
  });
});
