/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import InvoicesIndex 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}>
                                    {c.cell
                                        ? c.cell({
                                              row: {
                                                  original: r,
                                                  getValue: () =>
                                                      r[c.accessorKey],
                                              },
                                          })
                                        : String(r[c.accessorKey] ?? '')}
                                </td>
                            ))}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    ),
}));

vi.mock('@/components/admin/PageHeader', () => ({
    default: ({ title, description }: any) => (
        <div>
            <h2>{title}</h2>
            {description && <p>{description}</p>}
        </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_INVOICES = [
    {
        id: 'gg000001-0000-0000-0000-000000000001',
        invoice_number: 'INV-2025-0001',
        tenant_id: 'hh000001-0000-0000-0000-000000000001',
        tenant_name: 'Acme Corp',
        amount: 4900,
        tax_amount: 0,
        total: 4900,
        total_fmt: 'KES 4,900',
        currency: 'KES',
        status: 'paid',
        plan_name: 'Professional',
        due_date: '2025-06-15T00:00:00Z',
        paid_at: '2025-06-10T00:00:00Z',
        created_at: '2025-06-01T00:00:00Z',
    },
    {
        id: 'gg000002-0000-0000-0000-000000000002',
        invoice_number: 'INV-2025-0002',
        tenant_id: 'hh000002-0000-0000-0000-000000000002',
        tenant_name: 'Beta Ltd',
        amount: 990,
        tax_amount: 0,
        total: 990,
        total_fmt: 'KES 990',
        currency: 'KES',
        status: 'overdue',
        plan_name: 'Starter',
        due_date: '2025-05-01T00:00:00Z',
        paid_at: null,
        created_at: '2025-04-15T00:00:00Z',
    },
];

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

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

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

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

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

    it('renders column headers: Invoice, Tenant, Amount, Status, Due, Paid, Created', () => {
        render(<InvoicesIndex />);
        expect(screen.getByText('Invoice')).toBeInTheDocument();
        expect(screen.getByText('Tenant')).toBeInTheDocument();
        expect(screen.getByText('Amount')).toBeInTheDocument();
        expect(screen.getByText('Status')).toBeInTheDocument();
        expect(screen.getByText('Due')).toBeInTheDocument();
        expect(screen.getAllByText('Paid').length).toBeGreaterThan(0);
        expect(screen.getByText('Created')).toBeInTheDocument();
    });

    it('renders quick filter tabs: All, Draft, Sent, Paid, Overdue, Void', () => {
        render(<InvoicesIndex />);
        expect(screen.getByRole('button', { name: 'All' })).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Draft' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Sent' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Paid' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Overdue' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Void' }),
        ).toBeInTheDocument();
    });

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

        render(<InvoicesIndex />);
        expect(screen.getByText('INV-2025-0001')).toBeInTheDocument();
        expect(screen.getByText('INV-2025-0002')).toBeInTheDocument();
    });

    it('renders invoice amounts', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_INVOICES,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<InvoicesIndex />);
        expect(screen.getByText('KES 4,900')).toBeInTheDocument();
        expect(screen.getByText('KES 990')).toBeInTheDocument();
    });

    it('renders invoice status values', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_INVOICES,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<InvoicesIndex />);
        expect(screen.getByText('paid')).toBeInTheDocument();
        expect(screen.getByText('overdue')).toBeInTheDocument();
    });

    it('renders tenant names for invoices', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_INVOICES,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<InvoicesIndex />);
        expect(screen.getByText('Acme Corp')).toBeInTheDocument();
        expect(screen.getByText('Beta Ltd')).toBeInTheDocument();
    });

    it('shows an empty table when no data is returned', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: undefined,
            isLoading: false,
            isFetching: false,
        } as any);

        render(<InvoicesIndex />);
        const rows = screen.queryAllByRole('row');
        expect(rows.length).toBe(1); // only header row
    });
});
