/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import TenantsIndex 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 }: 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>
    ),
    // named re-export so TS types are satisfied
}));

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

vi.mock('@/components/admin/PlanBadge', () => ({
    default: ({ plan }: any) => <span data-testid="plan-badge">{plan}</span>,
}));

vi.mock('@/components/admin/TenantStatusBadge', () => ({
    default: ({ status }: any) => (
        <span data-testid="status-badge">{status}</span>
    ),
}));

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

// ── Helpers ───────────────────────────────────────────────────────────────────

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

const SAMPLE_TENANTS = [
    {
        id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
        name: 'Acme Corp',
        slug: 'acme-corp',
        plan: 'professional',
        status: 'active',
        member_count: 42,
        mrr_raw: 4900,
        mrr: 'KES 4,900',
        joined_at: '2025-01-15T00:00:00Z',
    },
    {
        id: 'b2c3d4e5-f6a7-8901-bcde-f12345678901',
        name: 'Beta Solutions',
        slug: 'beta-solutions',
        plan: 'starter',
        status: 'trial',
        member_count: 7,
        mrr_raw: 0,
        mrr: 'KES 0',
        joined_at: '2025-03-20T00:00:00Z',
    },
];

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

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

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

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

    it('renders column headers: Tenant, Plan, Status, Members, MRR, Joined', () => {
        render(<TenantsIndex />);
        expect(screen.getByText('Tenant')).toBeInTheDocument();
        expect(screen.getByText('Plan')).toBeInTheDocument();
        expect(screen.getByText('Status')).toBeInTheDocument();
        expect(screen.getByText('Members')).toBeInTheDocument();
        expect(screen.getByText('MRR')).toBeInTheDocument();
        expect(screen.getByText('Joined')).toBeInTheDocument();
    });

    it('renders tenant rows when useQuery returns data', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_TENANTS,
                meta: SAMPLE_META,
                filter_counts: { all: 2, active: 1, trial: 1 },
            },
            isLoading: false,
            isFetching: false,
        } as any);

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

    it('renders MRR values for loaded tenants', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: {
                data: SAMPLE_TENANTS,
                meta: SAMPLE_META,
                filter_counts: {},
            },
            isLoading: false,
            isFetching: false,
        } as any);

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

    it('renders description text under the heading', () => {
        render(<TenantsIndex />);
        expect(
            screen.getByText(/Browse, filter, and manage every organization/i),
        ).toBeInTheDocument();
    });

    it('passes empty data array to DataTable when query returns nothing', () => {
        vi.mocked(useQuery).mockReturnValueOnce({
            data: undefined,
            isLoading: false,
            isFetching: false,
        } as any);

        render(<TenantsIndex />);
        // Table renders but contains no body rows
        const rows = screen.queryAllByRole('row');
        // Only the header row is present
        expect(rows.length).toBe(1);
    });

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