/* eslint-disable @typescript-eslint/no-explicit-any */
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import PlansForm from '../Form/Index';

// ── Mocks ─────────────────────────────────────────────────────────────────────

const mockRouterVisit = vi.hoisted(() => vi.fn());

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: mockRouterVisit,
    },
    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('@/lib/api', () => ({
    api: {
        get: vi.fn(),
        post: vi.fn().mockResolvedValue({}),
        put: vi.fn().mockResolvedValue({}),
        patch: vi.fn(),
        delete: vi.fn(),
    },
}));

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));

// Radix-based components are real DOM — mock them as simple pass-throughs so
// JSDOM doesn't choke on unimplemented pointer events etc.
vi.mock('@/components/ui/checkbox', () => ({
    Checkbox: ({ checked, onCheckedChange, disabled, ...rest }: any) => (
        <input
            type="checkbox"
            checked={checked ?? false}
            disabled={disabled}
            onChange={(e) => onCheckedChange?.(e.target.checked)}
            {...rest}
        />
    ),
}));

vi.mock('@/components/ui/input', () => ({
    Input: ({ value, onChange, placeholder, type, disabled, ...rest }: any) => (
        <input
            value={value ?? ''}
            onChange={onChange}
            placeholder={placeholder}
            type={type ?? 'text'}
            disabled={disabled}
            {...rest}
        />
    ),
}));

vi.mock('@/components/ui/textarea', () => ({
    Textarea: ({ value, onChange, placeholder, rows, ...rest }: any) => (
        <textarea
            value={value ?? ''}
            onChange={onChange}
            placeholder={placeholder}
            rows={rows}
            {...rest}
        />
    ),
}));

vi.mock('@/components/ui/tabs', () => ({
    Tabs: ({ children }: any) => <div>{children}</div>,
    TabsList: ({ children }: any) => <div role="tablist">{children}</div>,
    TabsTrigger: ({ children, value }: any) => (
        <button role="tab" data-value={value}>
            {children}
        </button>
    ),
    TabsContent: ({ children, value }: any) => (
        <div data-testid={`tab-content-${value}`}>{children}</div>
    ),
}));

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

const modules = [
    {
        id: '019efe5c-2f8e-7038-9c63-25c49a749457',
        slug: 'lending',
        name: 'Lending',
        icon: 'CreditCard',
        sub_modules: [
            {
                id: 'sm-1',
                slug: 'lending.core',
                name: 'Lending Core',
                is_core: true,
            },
            {
                id: 'sm-2',
                slug: 'lending.products',
                name: 'Loan Products',
                is_core: false,
            },
            {
                id: 'sm-3',
                slug: 'lending.reports',
                name: 'Loan Reports',
                is_core: false,
            },
        ],
    },
    {
        id: '019efe5c-2f8e-7038-9c63-25c49a749458',
        slug: 'savings',
        name: 'Savings',
        icon: 'PiggyBank',
        sub_modules: [
            {
                id: 'sm-4',
                slug: 'savings.core',
                name: 'Savings Core',
                is_core: true,
            },
            {
                id: 'sm-5',
                slug: 'savings.products',
                name: 'Savings Products',
                is_core: false,
            },
        ],
    },
];

const limitKeys = [
    { key: 'max_branches', label: 'Max branches', unit: 'branches' },
    { key: 'max_staff_users', label: 'Max staff users', unit: 'users' },
    { key: 'max_active_loans', label: 'Max active loans', unit: 'loans' },
];

const existingPlan = {
    id: '019efe4a-9d05-7265-8fa2-21b7c3d107dd',
    slug: 'professional',
    name: 'Professional',
    description: 'Full-featured plan',
    price_monthly: 149,
    price_yearly: 1490,
    currency: 'USD',
    is_active: true,
    is_public: true,
    trial_days: 14,
    sort_order: 2,
    limits: { max_branches: 10, max_staff_users: 50, max_active_loans: null },
    sub_module_slugs: ['lending.products'],
};

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

describe('Plans/Form — create mode', () => {
    beforeEach(() => {
        vi.clearAllMocks();
    });

    it('renders inside AdminLayout with "New Plan" title', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByTestId('admin-layout')).toBeInTheDocument();
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'New Plan',
        );
    });

    it('shows "New Plan" heading', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(
            screen.getByRole('heading', { name: /New Plan/i }),
        ).toBeInTheDocument();
    });

    it('renders empty plan name input', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        const nameInput = screen.getByPlaceholderText('Professional');
        expect(nameInput).toHaveValue('');
    });

    it('renders empty slug input (enabled in create mode)', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        const slugInput = screen.getByPlaceholderText('professional');
        expect(slugInput).toHaveValue('');
        expect(slugInput).not.toBeDisabled();
    });

    it('renders monthly and yearly price inputs empty', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByPlaceholderText('149')).toBeInTheDocument();
        expect(screen.getByPlaceholderText('1490')).toBeInTheDocument();
    });

    it('renders all limit key fields in the limits tab', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByText('Max branches')).toBeInTheDocument();
        expect(screen.getByText('Max staff users')).toBeInTheDocument();
        expect(screen.getByText('Max active loans')).toBeInTheDocument();
    });

    it('renders module names in the modules tab', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByText('Lending')).toBeInTheDocument();
        expect(screen.getByText('Savings')).toBeInTheDocument();
    });

    it('renders sub-module names', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByText('Loan Products')).toBeInTheDocument();
        expect(screen.getByText('Savings Products')).toBeInTheDocument();
    });

    it('renders core sub-modules with "core" label', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        const coreLabels = screen.getAllByText('core');
        // lending.core and savings.core
        expect(coreLabels.length).toBeGreaterThanOrEqual(2);
    });

    it('shows "Create Plan" submit button in create mode', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(
            screen.getByRole('button', { name: /Create Plan/i }),
        ).toBeInTheDocument();
    });

    it('renders Active and public checkboxes', () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        expect(screen.getByText('Active')).toBeInTheDocument();
        expect(screen.getByText('Show on pricing page')).toBeInTheDocument();
    });

    it('navigates back when back button is clicked', async () => {
        render(<PlansForm modules={modules} limitKeys={limitKeys} />);
        // The back button has an ArrowLeft icon and no text label
        const backBtn = screen
            .getAllByRole('button')
            .find(
                (btn) => btn.querySelector('svg') && !btn.textContent?.trim(),
            );
        if (backBtn) {
            await userEvent.click(backBtn);
            expect(mockRouterVisit).toHaveBeenCalledWith('/admin/plans');
        }
    });
});

describe('Plans/Form — edit mode', () => {
    beforeEach(() => {
        vi.clearAllMocks();
    });

    it('renders "Edit Plan" heading in edit mode', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(
            screen.getByRole('heading', { name: /Edit Plan/i }),
        ).toBeInTheDocument();
    });

    it('pre-fills plan name', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(screen.getByDisplayValue('Professional')).toBeInTheDocument();
    });

    it('pre-fills slug and disables it in edit mode', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        const slugInput = screen.getByDisplayValue('professional');
        expect(slugInput).toBeDisabled();
    });

    it('pre-fills monthly price', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(screen.getByDisplayValue('149')).toBeInTheDocument();
    });

    it('pre-fills description', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(
            screen.getByDisplayValue('Full-featured plan'),
        ).toBeInTheDocument();
    });

    it('shows "Update Plan" submit button in edit mode', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(
            screen.getByRole('button', { name: /Update Plan/i }),
        ).toBeInTheDocument();
    });

    it('pre-fills limit field with existing value', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        expect(screen.getByDisplayValue('10')).toBeInTheDocument();
        expect(screen.getByDisplayValue('50')).toBeInTheDocument();
    });

    it('leaves null limits blank (Unlimited placeholder)', () => {
        render(
            <PlansForm
                plan={existingPlan}
                modules={modules}
                limitKeys={limitKeys}
            />,
        );
        const unlimitedInputs = screen
            .getAllByPlaceholderText('Unlimited')
            .filter((el) => (el as HTMLInputElement).value === '');
        expect(unlimitedInputs.length).toBeGreaterThan(0);
    });
});
