/**
 * Pack-4 (session 65af6a29) ReportTemplates tests:
 *  - F4FE-004: dialog uses useForm (tracked errors) not raw router.post
 *  - F4UXA-004: zero-sections validation — helper message + button disabled state
 */
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';

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>
    ),
    // useForm is NOT mocked — use the real implementation so the dialog state
    // behaves as it would in production. We test behavior, not mocked internals.
    usePage: () => ({
      props: {
        auth: { user: null },
        errors: {},
        flash: {},
        polling_interval_ms: 5000,
        sites: [],
      },
    }),
    router: { visit: vi.fn(), delete: vi.fn() },
  };
});

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

vi.mock('@/Components/ui/empty-state', () => ({
  EmptyState: ({
    title,
    primaryAction,
  }: {
    title: string;
    primaryAction?: { label: string; onClick?: () => void };
  }) => (
    <div data-testid="empty-state">
      <h3>{title}</h3>
      {primaryAction && (
        <button onClick={primaryAction.onClick}>{primaryAction.label}</button>
      )}
    </div>
  ),
}));

import ReportTemplatesIndex from './Index';

const mockProps = {
  templates: [],
  filters: {},
  counts: { total: 0, system: 0, user: 0 },
  pagination: { current_page: 1, last_page: 1, per_page: 20, total: 0, links: [] },
};

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

  // ── F4FE-004 ─────────────────────────────────────────────────────────────
  describe('F4FE-004: dialog uses useForm (error-tracking form)', () => {
    it('opens a dialog with an accessible Name field using a <Label> htmlFor', async () => {
      const user = userEvent.setup();
      render(<ReportTemplatesIndex {...mockProps} />);

      // getAllByRole since empty-state also renders a "Create Template" button
      const buttons = screen.getAllByRole('button', { name: 'Create Template' });
      await user.click(buttons[0]);

      // Dialog should be open with proper label association (not a raw <input>)
      const nameInput = screen.getByLabelText(/^Name/i);
      expect(nameInput).toBeInTheDocument();
      // Should be a real Input (not a bare input with hand-rolled classes)
      expect(nameInput.tagName.toLowerCase()).toBe('input');
    });

    it('Create Template submit button is disabled when name is empty', async () => {
      const user = userEvent.setup();
      render(<ReportTemplatesIndex {...mockProps} />);

      // getAllByRole — empty state also has a "Create Template" button
      const openBtns = screen.getAllByRole('button', { name: 'Create Template' });
      await user.click(openBtns[0]);

      // After opening, dialog has a submit button; it should be disabled (name is '')
      const dialogSubmitBtns = screen.getAllByRole('button', { name: /Create Template/i });
      // The submit button inside the dialog form
      const submitBtn = dialogSubmitBtns.find(
        (b) => b.getAttribute('type') === 'submit',
      );
      expect(submitBtn).toBeDefined();
      expect(submitBtn).toBeDisabled();
    });

    it('Create Template submit button becomes enabled when a name is typed', async () => {
      const user = userEvent.setup();
      render(<ReportTemplatesIndex {...mockProps} />);

      const openBtns = screen.getAllByRole('button', { name: 'Create Template' });
      await user.click(openBtns[0]);
      await user.type(screen.getByLabelText(/^Name/i), 'My Report');

      // After typing a name the submit should no longer be disabled
      // (sections still defaulted to 2 items, so not zero-sections blocked)
      const dialogSubmitBtns = screen.getAllByRole('button', { name: /Create Template/i });
      const submitBtn = dialogSubmitBtns.find(
        (b) => b.getAttribute('type') === 'submit',
      );
      expect(submitBtn).not.toBeDisabled();
    });
  });

  // ── F4UXA-004 ─────────────────────────────────────────────────────────────
  describe('F4UXA-004: zero-sections validation', () => {
    it('shows "Select at least one section" when all section checkboxes are unchecked', async () => {
      const user = userEvent.setup();
      render(<ReportTemplatesIndex {...mockProps} />);

      const openBtns = screen.getAllByRole('button', { name: 'Create Template' });
      await user.click(openBtns[0]);

      // Radix Checkbox renders as <button role="checkbox" aria-checked="true/false">.
      // Filter for those that are currently checked (aria-checked="true") and click them.
      const checkboxes = screen.getAllByRole('checkbox');
      for (const checkbox of checkboxes) {
        if (checkbox.getAttribute('aria-checked') === 'true') {
          await user.click(checkbox);
        }
      }

      expect(screen.getByText(/Select at least one section/i)).toBeInTheDocument();
    });

    it('disables Create Template submit button when no sections are selected', async () => {
      const user = userEvent.setup();
      render(<ReportTemplatesIndex {...mockProps} />);

      const openBtns = screen.getAllByRole('button', { name: 'Create Template' });
      await user.click(openBtns[0]);
      await user.type(screen.getByLabelText(/^Name/i), 'My Report');

      // Uncheck all Radix checkboxes (aria-checked="true")
      const checkboxes = screen.getAllByRole('checkbox');
      for (const checkbox of checkboxes) {
        if (checkbox.getAttribute('aria-checked') === 'true') {
          await user.click(checkbox);
        }
      }

      const allBtns = screen.getAllByRole('button', { name: /Create Template/i });
      const submitBtn = allBtns.find((b) => b.getAttribute('type') === 'submit');
      expect(submitBtn).toBeDisabled();
    });
  });
});
