/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import AnnouncementsIndex 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: {},
        },
    })),
    useForm: vi.fn((defaults: any) => ({
        data: defaults ?? {},
        setData: vi.fn(),
        post: vi.fn(),
        put: vi.fn(),
        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('@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_ANNOUNCEMENTS = [
    {
        id: 'dd000001-0000-0000-0000-000000000001',
        title: 'New Dashboard Released',
        body_excerpt: 'We shipped a completely redesigned dashboard.',
        published_at: '2025-05-01T00:00:00Z',
        status: 'published' as const,
        tags: ['dashboard', 'ui'],
        created_at: '2025-04-28T00:00:00Z',
    },
    {
        id: 'dd000002-0000-0000-0000-000000000002',
        title: 'Upcoming Maintenance',
        body_excerpt: 'Scheduled downtime on June 10.',
        published_at: null,
        status: 'draft' as const,
        tags: [],
        created_at: '2025-05-20T00:00:00Z',
    },
];

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

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

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

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

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

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

    it('renders column headers: Title, Status, Published, Created', () => {
        render(<AnnouncementsIndex />);
        expect(screen.getByText('Title')).toBeInTheDocument();
        expect(screen.getByText('Status')).toBeInTheDocument();
        expect(screen.getAllByText('Published').length).toBeGreaterThan(0);
        expect(screen.getByText('Created')).toBeInTheDocument();
    });

    it('renders quick filter tabs for Published, Scheduled, Draft', () => {
        render(<AnnouncementsIndex />);
        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 announcement rows when useQuery returns data', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_ANNOUNCEMENTS,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<AnnouncementsIndex />);
        expect(screen.getByText('New Dashboard Released')).toBeInTheDocument();
        expect(screen.getByText('Upcoming Maintenance')).toBeInTheDocument();
    });

    it('shows status values for announcement rows', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_ANNOUNCEMENTS,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<AnnouncementsIndex />);
        expect(screen.getByText('published')).toBeInTheDocument();
        expect(screen.getByText('draft')).toBeInTheDocument();
    });
});
