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

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: {},
        },
    })),
}));

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

vi.mock('@tanstack/react-query', () => ({
    useQuery: vi.fn(() => ({
        data: undefined,
        isLoading: false,
        isFetching: false,
        isError: false,
        refetch: vi.fn(),
    })),
    useQueryClient: vi.fn(() => ({
        invalidateQueries: vi.fn(),
        setQueryData: vi.fn(),
    })),
    keepPreviousData: undefined,
}));

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/DataTable', () => ({
    DataTable: ({ columns, data, quickFilters }: any) => (
        <div>
            {quickFilters?.map((f: any) => (
                <button key={f.value}>{f.label}</button>
            ))}
            <table>
                <thead>
                    <tr>
                        {columns.map((c: any) => (
                            <th key={c.accessorKey ?? c.id}>{c.header}</th>
                        ))}
                    </tr>
                </thead>
                <tbody>
                    {(data ?? []).map((r: any, i: number) => (
                        <tr key={i}>
                            {columns.map((c: any, j: number) => (
                                <td key={j}>
                                    {String(r[c.accessorKey] ?? '')}
                                </td>
                            ))}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    ),
}));

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

vi.mock('@/hooks/useDataTable', () => ({
    useDataTable: () => ({
        params: {
            page: 1,
            sort: 'created_at',
            dir: 'desc',
            search: '',
            filter: 'all',
        },
        setParams: vi.fn(),
    }),
}));

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

import { useQuery } from '@tanstack/react-query';

const SAMPLE_JOB_OPENINGS = [
    {
        id: 'dd000001-0000-0000-0000-000000000001',
        title: 'Senior Backend Engineer',
        team: 'Engineering',
        location: 'Nairobi / Remote',
        employment_type: 'Full-time',
        published_at: '2025-05-01',
        status: 'published' as const,
        created_at: '2025-04-28',
    },
    {
        id: 'dd000002-0000-0000-0000-000000000002',
        title: 'Draft Role',
        team: null,
        location: null,
        employment_type: null,
        published_at: null,
        status: 'draft' as const,
        created_at: '2025-05-20',
    },
];

const SAMPLE_META = {
    current_page: 1,
    last_page: 1,
    total: 2,
    per_page: 25,
    from: 1,
    to: 2,
};

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

describe('Admin/JobOpenings/Index', () => {
    it('renders inside AdminLayout without crashing', () => {
        render(<JobOpeningsIndex />);
        expect(screen.getByTestId('admin-layout')).toBeInTheDocument();
    });

    it('sets AdminLayout title to "Careers"', () => {
        render(<JobOpeningsIndex />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'Careers',
        );
    });

    it('shows the "Careers" heading', () => {
        render(<JobOpeningsIndex />);
        expect(
            screen.getByRole('heading', { name: 'Careers' }),
        ).toBeInTheDocument();
    });

    it('renders a "New job opening" link button', () => {
        render(<JobOpeningsIndex />);
        expect(
            screen.getByRole('link', { name: /new job opening/i }),
        ).toHaveAttribute('href', '/admin/careers/create');
    });

    it('renders quick filter tabs for Published, Scheduled, Draft', () => {
        render(<JobOpeningsIndex />);
        expect(screen.getByRole('button', { name: 'All' })).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Published' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Scheduled' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Draft' }),
        ).toBeInTheDocument();
    });

    it('renders job opening rows when useQuery returns data', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_JOB_OPENINGS,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<JobOpeningsIndex />);
        expect(screen.getByText('Senior Backend Engineer')).toBeInTheDocument();
        expect(screen.getByText('Draft Role')).toBeInTheDocument();
    });
});
