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

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

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().mockResolvedValue({}),
        delete: vi.fn().mockResolvedValue({}),
    },
}));

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}>
                                {typeof c.header === 'string' ? 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 data-testid="page-header">
            <h2>{title}</h2>
            {description && <p>{description}</p>}
            {action && <div>{action}</div>}
        </div>
    ),
}));

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

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

const SAMPLE_CURRENCIES = [
    {
        id: '019efe4a-9d05-7265-8fa2-21b7c3d10800',
        code: 'USD',
        name: 'US Dollar',
        symbol: '$',
        rate: 1,
        decimals: 2,
        is_base: true,
        is_enabled: true,
        sort_order: 0,
        created_at: '2026-07-01T00:00:00Z',
    },
    {
        id: '019efe4a-9d05-7265-8fa2-21b7c3d10801',
        code: 'KES',
        name: 'Kenyan Shilling',
        symbol: 'KSh',
        rate: 129,
        decimals: 0,
        is_base: false,
        is_enabled: true,
        sort_order: 1,
        created_at: '2026-07-01T00:00:00Z',
    },
];

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

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

describe('Admin/Currencies/Index', () => {
    it('renders inside AdminLayout with Currencies title', () => {
        render(<CurrenciesIndex />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'Currencies',
        );
    });

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

    it('renders a New Currency link button', () => {
        render(<CurrenciesIndex />);
        expect(
            screen.getByRole('link', { name: /new currency/i }),
        ).toHaveAttribute('href', '/admin/currencies/create');
    });

    it('renders a Trash link', () => {
        render(<CurrenciesIndex />);
        expect(screen.getByRole('link', { name: /trash/i })).toHaveAttribute(
            'href',
            '/admin/currencies/trash',
        );
    });

    it('renders quick filter tabs for All, Enabled, Disabled', () => {
        render(<CurrenciesIndex />);
        expect(screen.getByRole('button', { name: 'All' })).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Enabled' }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: 'Disabled' }),
        ).toBeInTheDocument();
    });

    it('renders currency rows when useQuery returns data', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_CURRENCIES,
                meta: SAMPLE_META,
                filter_counts: { all: 2, enabled: 2, disabled: 0 },
            },
            isLoading: false,
            isFetching: false,
        } as any);

        render(<CurrenciesIndex />);
        expect(screen.getByText('USD')).toBeInTheDocument();
        expect(screen.getByText('KES')).toBeInTheDocument();
        expect(screen.getByText('Kenyan Shilling')).toBeInTheDocument();
    });

    it('renders table column headers', () => {
        render(<CurrenciesIndex />);
        expect(screen.getByText('Code')).toBeInTheDocument();
        expect(screen.getByText('Rate per base unit')).toBeInTheDocument();
        expect(screen.getByText('Decimals')).toBeInTheDocument();
        expect(screen.getByText('Status')).toBeInTheDocument();
    });
});
