/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import BillingComponent from '../Billing';
const Billing = BillingComponent 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: {},
            currency: {
                current: 'USD',
                base: 'USD',
                available: [
                    {
                        code: 'USD',
                        name: 'US Dollar',
                        symbol: '$',
                        rate: 1,
                        decimals: 2,
                    },
                ],
            },
            ziggy: {
                url: 'http://localhost',
                port: null,
                defaults: [],
                routes: {},
            },
        },
    })),
    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/ClientLayout', () => ({
    default: ({ children }: any) => (
        <div data-testid="client-layout">{children}</div>
    ),
}));

vi.mock('../components/AppNav', () => ({
    default: () => <nav data-testid="app-nav" />,
}));

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

const app = {
    id: 'tenant-abc',
    name: 'Kilimo SACCO',
    orgType: 'sacco',
    country: 'TZ',
    subdomain: 'kilimo',
    domain: 'kilimo.upepofinance.com',
    portalUrl: null,
    plan: null,
    planStatus: null,
    billingCycle: null,
    trialEndsAt: null,
    currentPeriodEnd: null,
    setupComplete: true,
};

const plans = [
    {
        id: 1,
        name: 'Starter',
        priceMonthly: 49000,
        priceYearly: 44100,
        description: 'For small SACCOs',
        trialDays: 30,
        limits: {
            maxBranches: 2,
            maxStaffUsers: 10,
            maxActiveBorrowers: 500,
            maxActiveLoans: 300,
        },
    },
    {
        id: 2,
        name: 'Professional',
        priceMonthly: 149000,
        priceYearly: 134100,
        description: 'For growing MFIs',
        trialDays: 30,
        limits: {
            maxBranches: 10,
            maxStaffUsers: 30,
            maxActiveBorrowers: 5000,
            maxActiveLoans: 3000,
        },
    },
];

const subscription = {
    planId: 1,
    planName: 'Starter',
    status: 'active',
    billingCycle: 'monthly',
    trialEndsAt: null,
    currentPeriodEnd: '2026-07-15',
};

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

    it('renders inside ClientLayout', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={subscription as any}
            />,
        );
        expect(screen.getByTestId('client-layout')).toBeInTheDocument();
    });

    it('renders AppNav', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={subscription as any}
            />,
        );
        expect(screen.getByTestId('app-nav')).toBeInTheDocument();
    });

    it('shows current subscription summary when a subscription exists', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={subscription as any}
            />,
        );
        expect(screen.getByText('Current plan')).toBeInTheDocument();
        expect(screen.getAllByText('Starter').length).toBeGreaterThan(0);
    });

    it('renders billing cycle toggle buttons', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={subscription as any}
            />,
        );
        expect(
            screen.getByRole('button', { name: /monthly/i }),
        ).toBeInTheDocument();
        expect(
            screen.getByRole('button', { name: /yearly/i }),
        ).toBeInTheDocument();
    });

    it('renders plan selection cards', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={subscription as any}
            />,
        );
        expect(screen.getByText('Professional')).toBeInTheDocument();
        expect(screen.getByText(/\$49,000/)).toBeInTheDocument();
    });

    it('shows "No plans available" message when plans array is empty', () => {
        render(<Billing app={app as any} plans={[]} subscription={null} />);
        expect(screen.getByText(/no plans available/i)).toBeInTheDocument();
    });

    it('shows "Select a plan" heading when no subscription exists', () => {
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={null}
            />,
        );
        expect(screen.getByText('Select a plan')).toBeInTheDocument();
    });

    it('shows trial days badge when subscription is trialing', () => {
        const trialSub = {
            ...subscription,
            status: 'trialing',
            trialEndsAt: new Date(Date.now() + 10 * 86_400_000).toISOString(),
        };
        render(
            <Billing
                app={app as any}
                plans={plans as any}
                subscription={trialSub as any}
            />,
        );
        expect(screen.getByText(/d left/)).toBeInTheDocument();
    });
});
