/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import ArticleForm from '../Form';

// ── Mocks ─────────────────────────────────────────────────────────────────────

const mockPost = vi.fn();
const mockPut = vi.fn();
const mockSetData = vi.fn();

vi.mock('@inertiajs/react', () => ({
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ href, children, ...rest }: any) => (
        <a href={href} {...rest}>
            {children}
        </a>
    ),
    router: {
        get: vi.fn(),
        post: vi.fn(),
        put: vi.fn(),
        patch: vi.fn(),
        delete: vi.fn(),
        visit: vi.fn(),
    },
    usePage: vi.fn(() => ({
        props: {
            auth: { adminRole: 'super_admin', adminPermissions: [] },
            flash: {},
            errors: {},
        },
    })),
    useForm: vi.fn((defaults: any) => ({
        data: { ...defaults },
        setData: mockSetData,
        post: mockPost,
        put: mockPut,
        patch: vi.fn(),
        delete: vi.fn(),
        processing: false,
        errors: {},
        reset: vi.fn(),
        transform: vi.fn().mockReturnThis(),
    })),
}));

vi.mock('@/Layouts/AdminLayout', () => ({
    default: ({ children, title }: any) => (
        <div data-testid="admin-layout" data-title={title}>
            {children}
        </div>
    ),
}));

vi.mock('@/lib/api', () => ({
    api: {
        get: vi.fn(),
        post: vi.fn(),
        put: vi.fn(),
        patch: vi.fn(),
        delete: vi.fn(),
    },
}));

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

vi.mock('@/components/admin/PageHeader', () => ({
    default: ({ title }: any) => <h2>{title}</h2>,
}));

vi.mock('@/components/admin/RichTextEditor', () => ({
    RichTextEditor: ({ value, placeholder }: any) => (
        <textarea
            aria-label="Body"
            placeholder={placeholder}
            value={value}
            readOnly
        />
    ),
}));

// ── Fixtures ──────────────────────────────────────────────────────────────────

const EXISTING_ARTICLE = {
    id: 'dd000001-0000-0000-0000-000000000001',
    type: 'news',
    title: 'Upepo raises seed round',
    slug: 'upepo-raises-seed-round',
    excerpt: 'Big news for the company.',
    body: 'Full story here.',
    category: null,
    tags: 'funding, press',
    published_at: '2025-06-01T10:00',
    status: 'published',
    cover_url: null,
    created_at: '2025-05-28T00:00:00Z',
    outlet: 'TechCrunch',
};

// ── Tests ─────────────────────────────────────────────────────────────────────

describe('Admin/Articles/Form — create mode', () => {
    it('renders inside AdminLayout without crashing', () => {
        render(<ArticleForm />);
        expect(screen.getByTestId('admin-layout')).toBeInTheDocument();
    });

    it('sets AdminLayout title to "New Article" in create mode', () => {
        render(<ArticleForm />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'New Article',
        );
    });

    it('shows "New Article" heading in create mode', () => {
        render(<ArticleForm />);
        expect(
            screen.getByRole('heading', { name: 'New Article' }),
        ).toBeInTheDocument();
    });

    it('renders a blank title input in create mode', () => {
        render(<ArticleForm />);
        const titleInput = screen.getByPlaceholderText('Article title');
        expect(titleInput).toBeInTheDocument();
        expect(titleInput).toHaveValue('');
    });

    it('defaults the type select to News, showing the Outlet field', () => {
        render(<ArticleForm />);
        expect(
            screen.getByPlaceholderText('e.g. TechCrunch'),
        ).toBeInTheDocument();
    });

    it('renders a tags input with comma-separated hint', () => {
        render(<ArticleForm />);
        expect(
            screen.getByText(/Separate multiple tags with commas/i),
        ).toBeInTheDocument();
    });

    it('renders a publish date input with helper text', () => {
        render(<ArticleForm />);
        expect(
            screen.getByText(/Leave blank to save as draft/i),
        ).toBeInTheDocument();
    });

    it('renders a "Save draft" submit button when no publish date is set', () => {
        render(<ArticleForm />);
        expect(
            screen.getByRole('button', { name: /save draft/i }),
        ).toBeInTheDocument();
    });

    it('renders a Cancel link back to /admin/articles', () => {
        render(<ArticleForm />);
        expect(screen.getByRole('link', { name: /cancel/i })).toHaveAttribute(
            'href',
            '/admin/articles',
        );
    });
});

describe('Admin/Articles/Form — edit mode', () => {
    it('sets AdminLayout title to "Edit Article" in edit mode', () => {
        render(<ArticleForm article={EXISTING_ARTICLE as any} />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'Edit Article',
        );
    });

    it('pre-fills the title input with the existing title', () => {
        render(<ArticleForm article={EXISTING_ARTICLE as any} />);
        expect(screen.getByPlaceholderText('Article title')).toHaveValue(
            'Upepo raises seed round',
        );
    });

    it('pre-fills the outlet field for a news article', () => {
        render(<ArticleForm article={EXISTING_ARTICLE as any} />);
        expect(screen.getByPlaceholderText('e.g. TechCrunch')).toHaveValue(
            'TechCrunch',
        );
    });

    it('pre-fills the tags input with existing tags', () => {
        render(<ArticleForm article={EXISTING_ARTICLE as any} />);
        expect(
            screen.getByPlaceholderText(/billing, mobile, api/i),
        ).toHaveValue('funding, press');
    });

    it('shows "Update" submit button in edit mode when publish date is set', () => {
        render(<ArticleForm article={EXISTING_ARTICLE as any} />);
        expect(
            screen.getByRole('button', { name: /update/i }),
        ).toBeInTheDocument();
    });
});
