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

import ContentHistoryIndex from '@/Pages/ContentHistory/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>
    ),
    usePage: vi.fn(() => ({
      props: {
        auth: { user: { name: 'Test User', email: 'test@example.com' } },
        features: { billing: false, notifications: false },
        sites: [],
        limits: null,
        ai_defaults: { model: 'gpt-4o-mini', temperature: 0.7 },
      },
    })),
    router: { reload: vi.fn() },
  };
});

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/ContentHistory/SnapshotList', () => ({
  default: ({
    snapshots,
    currentSnapshotId,
    onRollback,
  }: {
    snapshots: Array<{ id: number; title: string }>;
    currentSnapshotId?: number;
    onRollback: (snapshot: { id: number; title: string }) => void;
  }) => (
    <div data-testid="snapshot-list">
      <span data-testid="snapshot-count">{snapshots.length}</span>
      <span data-testid="current-snapshot-id">{currentSnapshotId}</span>
      {snapshots.map((snapshot) => (
        <button
          key={snapshot.id}
          data-testid={`rollback-btn-${snapshot.id}`}
          onClick={() => onRollback(snapshot)}
        >
          Rollback {snapshot.id}
        </button>
      ))}
    </div>
  ),
}));

vi.mock('@/Components/ContentHistory/RollbackConfirmModal', () => ({
  default: ({
    open,
    onOpenChange,
    snapshotId,
    currentSnapshot,
    targetSnapshot,
  }: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    snapshotId: number;
    currentSnapshot: { id: number };
    targetSnapshot: { id: number };
  }) =>
    open ? (
      <div data-testid="rollback-modal">
        <span data-testid="modal-snapshot-id">{snapshotId}</span>
        <span data-testid="modal-current-id">{currentSnapshot.id}</span>
        <span data-testid="modal-target-id">{targetSnapshot.id}</span>
        <button data-testid="close-modal" onClick={() => onOpenChange(false)}>
          Close
        </button>
      </div>
    ) : null,
}));

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

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

const baseWpPost = {
  id: 5,
  wp_post_id: 123,
  url: 'https://test.com/blog/seo-guide',
  title: 'Ultimate SEO Guide',
  content: '<p>Original content</p>',
  meta_description: 'SEO guide meta description',
  seo_meta_title: 'SEO Guide | Test Site',
  post_status: 'publish',
  wp_modified_at: '2026-01-15T12:00:00Z',
};

const baseSnapshots = [
  {
    id: 101,
    title: 'Ultimate SEO Guide',
    content: '<p>Current version content</p>',
    url: 'https://test.com/blog/seo-guide',
    meta_description: 'Current meta',
    seo_meta_title: 'SEO Guide | Test Site',
    seo_robots: null,
    categories: ['SEO', 'Marketing'],
    tags: ['seo', 'guide'],
    wp_post_status: 'publish',
    wp_modified_at: '2026-01-15T12:00:00Z',
    created_at: '2026-01-15T12:00:00Z',
  },
  {
    id: 100,
    title: 'Ultimate SEO Guide - Old',
    content: '<p>Previous version content</p>',
    url: 'https://test.com/blog/seo-guide',
    meta_description: 'Old meta',
    seo_meta_title: 'SEO Guide | Test Site',
    seo_robots: null,
    categories: ['SEO'],
    tags: ['seo'],
    wp_post_status: 'publish',
    wp_modified_at: '2026-01-10T10:00:00Z',
    created_at: '2026-01-10T10:00:00Z',
  },
];

describe('ContentHistory/Index', () => {
  describe('page title', () => {
    it('renders page title with site name and post title', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(document.querySelector('title')).toHaveTextContent(
        'Test Site - Content History - Ultimate SEO Guide',
      );
    });
  });

  describe('navigation', () => {
    it('renders SiteNav component', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

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

    it('renders back to content inventory link', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      const backLink = screen.getByRole('link', { name: /back to content inventory/i });
      expect(backLink).toBeInTheDocument();
    });
  });

  describe('page header', () => {
    it('renders heading with "Content History"', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByRole('heading', { name: 'Content History' })).toBeInTheDocument();
    });

    it('renders WP post title', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByText('Ultimate SEO Guide')).toBeInTheDocument();
    });

    it('renders WP post URL', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByText('https://test.com/blog/seo-guide')).toBeInTheDocument();
    });
  });

  describe('SnapshotList component', () => {
    it('renders SnapshotList with snapshots', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByTestId('snapshot-list')).toBeInTheDocument();
    });

    it('passes snapshots to SnapshotList', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByTestId('snapshot-count')).toHaveTextContent('2');
    });

    it('passes current snapshot ID (first in list)', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.getByTestId('current-snapshot-id')).toHaveTextContent('101');
    });

    it('renders SnapshotList with empty snapshots array', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={[]} />);

      expect(screen.getByTestId('snapshot-list')).toBeInTheDocument();
      expect(screen.getByTestId('snapshot-count')).toHaveTextContent('0');
    });
  });

  describe('rollback modal', () => {
    it('does not render modal by default', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      expect(screen.queryByTestId('rollback-modal')).not.toBeInTheDocument();
    });

    it('opens modal when rollback is triggered', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      const rollbackBtn = screen.getByTestId('rollback-btn-100');
      fireEvent.click(rollbackBtn);

      expect(screen.getByTestId('rollback-modal')).toBeInTheDocument();
    });

    it('passes correct snapshot IDs to modal', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      const rollbackBtn = screen.getByTestId('rollback-btn-100');
      fireEvent.click(rollbackBtn);

      expect(screen.getByTestId('modal-snapshot-id')).toHaveTextContent('100');
      expect(screen.getByTestId('modal-current-id')).toHaveTextContent('101');
      expect(screen.getByTestId('modal-target-id')).toHaveTextContent('100');
    });

    it('closes modal when close is triggered', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={baseSnapshots} />);

      const rollbackBtn = screen.getByTestId('rollback-btn-100');
      fireEvent.click(rollbackBtn);
      expect(screen.getByTestId('rollback-modal')).toBeInTheDocument();

      const closeBtn = screen.getByTestId('close-modal');
      fireEvent.click(closeBtn);

      expect(screen.queryByTestId('rollback-modal')).not.toBeInTheDocument();
    });

    it('does not render modal when snapshots array is empty', () => {
      render(<ContentHistoryIndex site={baseSite} wpPost={baseWpPost} snapshots={[]} />);

      expect(screen.queryByTestId('rollback-modal')).not.toBeInTheDocument();
    });
  });

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