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

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

const TENANT = {
    id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
    name: 'Acme Corp',
    country: 'KE',
    org_type: 'sacco',
    joined_at: '2024-06-01T00:00:00Z',
    status: 'active',
    domains: [
        { domain: 'acme.example.com', is_primary: true, ssl_status: 'active' },
    ],
    owner: {
        id: 'user-1',
        name: 'Wanjiku Kamau',
        email: 'wanjiku@example.com',
        avatar: null,
    },
};

const SUBSCRIPTION = {
    status: 'active',
    billing_cycle: 'monthly',
    trial_ends_at: null,
    current_period_start: '2025-06-01T00:00:00Z',
    current_period_end: '2025-07-01T00:00:00Z',
    suspended_at: null,
    plan: {
        id: 'plan-1',
        name: 'Professional',
        slug: 'professional',
        price_monthly: 4900,
        price_yearly: 49000,
        currency: 'KES',
    },
    mrr_raw: 4900,
    mrr: 'KES 4,900',
};

const MEMBERS = [
    {
        id: 'user-1',
        name: 'Wanjiku Kamau',
        email: 'wanjiku@example.com',
        avatar: null,
        is_owner: true,
        status: 'active',
        joined_at: '2024-06-01T00:00:00Z',
    },
];

const USAGE = {
    meters: [],
    module_overrides: [],
    limit_override: null,
};

const PLANS = [
    {
        id: 'plan-1',
        name: 'Professional',
        slug: 'professional',
        price_monthly: 4900,
        price_yearly: 49000,
        currency: 'KES',
    },
];

const DEFAULT_PROPS: React.ComponentProps<typeof TenantsShow> = {
    tenant: TENANT,
    members: MEMBERS,
    subscription: SUBSCRIPTION,
    invoices: [],
    usage: USAGE,
    activity: [],
    plans: PLANS,
};

function renderShow(overrides: Partial<typeof DEFAULT_PROPS> = {}) {
    return render(<TenantsShow {...DEFAULT_PROPS} {...overrides} />);
}

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

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

    it('sets AdminLayout title to the tenant name', () => {
        renderShow();
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'Acme Corp',
        );
    });

    it('displays the tenant name as the page h1', () => {
        renderShow();
        expect(
            screen.getByRole('heading', { name: 'Acme Corp' }),
        ).toBeInTheDocument();
    });

    it('shows the tenant status badge', () => {
        renderShow();
        expect(screen.getByTestId('status-badge')).toHaveTextContent('active');
    });

    it('shows the plan badge with plan name', () => {
        renderShow();
        expect(screen.getByTestId('plan-badge')).toHaveTextContent(
            'Professional',
        );
    });

    it('displays "Billed monthly" for monthly billing cycle', () => {
        renderShow();
        expect(screen.getByText('Billed monthly')).toBeInTheDocument();
    });

    it('displays the MRR value', () => {
        renderShow();
        expect(screen.getByText('KES 4,900')).toBeInTheDocument();
    });

    it('renders "Kenya" for country code KE', () => {
        renderShow();
        expect(screen.getByText('Kenya')).toBeInTheDocument();
    });

    it('renders the org type label', () => {
        renderShow();
        expect(screen.getByText('SACCO')).toBeInTheDocument();
    });

    it('renders domain with primary badge', () => {
        renderShow();
        expect(screen.getByText('acme.example.com')).toBeInTheDocument();
        expect(screen.getByText('primary')).toBeInTheDocument();
    });

    it('links the owner to their client page', () => {
        renderShow();
        const ownerLink = screen
            .getAllByRole('link')
            .find((l) => l.getAttribute('href') === '/admin/clients/user-1');
        expect(ownerLink).toBeDefined();
        expect(screen.getAllByText('Wanjiku Kamau').length).toBeGreaterThan(0);
    });

    it('shows the team tab with the member count', () => {
        renderShow();
        expect(
            screen.getByRole('tab', { name: /team \(1\)/i }),
        ).toBeInTheDocument();
    });

    it('shows "No subscription yet" when subscription is null', () => {
        renderShow({ subscription: null });
        expect(screen.getByText('No subscription yet')).toBeInTheDocument();
    });

    it('renders a back link to /admin/tenants', () => {
        renderShow();
        expect(
            screen.getByRole('link', { name: /all tenants/i }),
        ).toHaveAttribute('href', '/admin/tenants');
    });

    it('shows "Billed yearly" label for yearly billing cycle', () => {
        renderShow({
            subscription: { ...SUBSCRIPTION, billing_cycle: 'yearly' },
        });
        expect(screen.getByText('Billed yearly')).toBeInTheDocument();
    });

    it('shows an Actions menu button', () => {
        renderShow();
        expect(
            screen.getByRole('button', { name: /actions/i }),
        ).toBeInTheDocument();
    });
});
