/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import DashboardComponent from '../Dashboard/Index';
const Dashboard = DashboardComponent as any;

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: {
                user: { id: '1', name: 'Test User', email: 'test@example.com' },
            },
            flash: {},
            errors: {},
            ziggy: {
                url: 'http://localhost',
                port: null,
                defaults: [],
                routes: {},
            },
        },
    })),
    useForm: vi.fn(() => ({
        data: {},
        setData: vi.fn(),
        post: vi.fn(),
        processing: false,
        errors: {},
        reset: vi.fn(),
    })),
}));

vi.mock('@/Layouts/ClientLayout', () => ({
    default: ({ children }: any) => (
        <div data-testid="client-layout">{children}</div>
    ),
}));

// DataTable is a complex table — stub it to render only what we need
vi.mock('@/components/admin/DataTable', () => ({
    DataTable: ({ data, quickFilters, searchPlaceholder }: any) => (
        <div data-testid="data-table">
            <input placeholder={searchPlaceholder} />
            {quickFilters?.map((f: any) => (
                <button key={f.value} type="button">
                    {f.label} ({f.count})
                </button>
            ))}
            {data.map((row: any) => (
                <div key={row.id} data-testid="table-row">
                    {row.name}
                </div>
            ))}
        </div>
    ),
}));

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

vi.stubGlobal('route', (name: string) => `/${name}`);

const tenants = [
    {
        id: 'aaa',
        name: 'Kilimo SACCO',
        orgType: 'sacco',
        country: 'TZ',
        domain: 'kilimo.upepofinance.com',
        plan: 'Professional',
        planStatus: 'active',
        setupComplete: true,
        trialEndsAt: null,
        nextStep: null,
        portalUrl: 'https://kilimo.upepofinance.com',
    },
    {
        id: 'bbb',
        name: 'Maziwa MFI',
        orgType: 'microfinance',
        country: 'KE',
        domain: null,
        plan: null,
        planStatus: null,
        setupComplete: false,
        trialEndsAt: null,
        nextStep: '/setup/organisation/bbb',
        portalUrl: null,
    },
];

describe('Dashboard page', () => {
    beforeEach(() => {
        vi.clearAllMocks();
    });

    it('renders the empty state when no tenants exist', () => {
        render(<Dashboard tenants={[]} createHref="/setup/organisation/new" />);
        expect(screen.getByText('No apps yet')).toBeInTheDocument();
        expect(screen.getByText('Create your first app')).toBeInTheDocument();
    });

    it('renders "My Apps" heading when tenants exist', () => {
        render(
            <Dashboard
                tenants={tenants as any}
                createHref="/setup/organisation/new"
            />,
        );
        expect(
            screen.getByRole('heading', { name: 'My Apps' }),
        ).toBeInTheDocument();
    });

    it('renders the DataTable with tenants', () => {
        render(
            <Dashboard
                tenants={tenants as any}
                createHref="/setup/organisation/new"
            />,
        );
        expect(screen.getByTestId('data-table')).toBeInTheDocument();
        expect(screen.getByText('Kilimo SACCO')).toBeInTheDocument();
        expect(screen.getByText('Maziwa MFI')).toBeInTheDocument();
    });

    it('shows quick filter buttons with correct counts', () => {
        render(
            <Dashboard
                tenants={tenants as any}
                createHref="/setup/organisation/new"
            />,
        );
        expect(
            screen.getByRole('button', { name: /all \(2\)/i }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: /live \(1\)/i }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: /setup pending \(1\)/i }),
        ).toBeInTheDocument();
    });

    it('renders "New app" button linking to createHref', () => {
        render(
            <Dashboard
                tenants={tenants as any}
                createHref="/setup/organisation/new"
            />,
        );
        expect(screen.getByText('New app')).toBeInTheDocument();
    });

    it('shows app count in subtitle', () => {
        render(
            <Dashboard
                tenants={tenants as any}
                createHref="/setup/organisation/new"
            />,
        );
        expect(screen.getByText(/2 apps · 1 live/i)).toBeInTheDocument();
    });

    it('shows trust badges in empty state', () => {
        render(<Dashboard tenants={[]} createHref="/setup/organisation/new" />);
        expect(screen.getByText('AES-256 encryption')).toBeInTheDocument();
        expect(screen.getByText('GDPR compliant')).toBeInTheDocument();
    });
});
