/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import ClientsIndex 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 }: any) => (
        <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>
    ),
}));

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

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

const SAMPLE_CLIENTS = [
    {
        id: 'user-1',
        name: 'Wanjiku Kamau',
        email: 'wanjiku@example.com',
        avatar: null,
        provider: 'email',
        verified: true,
        owned_apps_count: 2,
        member_apps_count: 3,
        joined_at: '2025-01-15T00:00:00Z',
    },
];

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

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

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

    it('renders column headers: Client, Signup, Verified, Tenants, Joined', () => {
        render(<ClientsIndex />);
        expect(screen.getByText('Client')).toBeInTheDocument();
        expect(screen.getByText('Signup')).toBeInTheDocument();
        expect(screen.getByText('Verified')).toBeInTheDocument();
        expect(screen.getByText('Tenants')).toBeInTheDocument();
        expect(screen.getByText('Joined')).toBeInTheDocument();
    });

    it('renders client rows when useQuery returns data', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_CLIENTS,
                meta: SAMPLE_META,
                filter_counts: { all: 1 },
            },
            isLoading: false,
            isFetching: false,
            isError: false,
            refetch: vi.fn(),
        } as any);

        render(<ClientsIndex />);
        expect(screen.getByText('Wanjiku Kamau')).toBeInTheDocument();
    });
});
