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

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

const mockPost = vi.fn();
const mockPut = vi.fn();
const mockSetData = 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: vi.fn(),
    },
    usePage: vi.fn(() => ({
        props: {
            auth: { adminRole: 'super_admin', adminPermissions: [] },
            flash: {},
            errors: {},
        },
    })),
    useForm: vi.fn((defaults: any) => ({
        data: { ...defaults },
        setData: mockSetData,
        post: mockPost,
        put: mockPut,
        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(),
        put: vi.fn(),
        patch: vi.fn(),
        delete: vi.fn(),
    },
}));

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

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

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

const EXISTING_CUSTOMER = {
    id: 'cc000001-0000-0000-0000-000000000001',
    name: 'Mwanga Microfinance',
    sector: 'Microfinance Institution',
    country: 'Kenya',
    location: 'Nairobi',
    website: 'https://mwanga.example.org',
    description: 'Serving smallholder farmers across central Kenya.',
    since_year: 2021,
    published_at: '2025-06-01T10:00',
    status: 'published',
    logo_url: null,
    created_at: '2025-05-28T00:00:00Z',
};

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

describe('Admin/Customers/Form — create mode', () => {
    it('renders inside AdminLayout without crashing', () => {
        render(<CustomerForm />);
        expect(screen.getByTestId('admin-layout')).toBeInTheDocument();
    });

    it('sets AdminLayout title to "New Customer" in create mode', () => {
        render(<CustomerForm />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'New Customer',
        );
    });

    it('shows "New Customer" heading in create mode', () => {
        render(<CustomerForm />);
        expect(
            screen.getByRole('heading', { name: 'New Customer' }),
        ).toBeInTheDocument();
    });

    it('renders a blank name input in create mode', () => {
        render(<CustomerForm />);
        const nameInput = screen.getByPlaceholderText(
            'e.g. Mwanga Microfinance',
        );
        expect(nameInput).toBeInTheDocument();
        expect(nameInput).toHaveValue('');
    });

    it('renders a publish date input with helper text', () => {
        render(<CustomerForm />);
        expect(
            screen.getByText(/Leave blank to save as draft/i),
        ).toBeInTheDocument();
    });

    it('renders a "Save draft" submit button when no publish date is set', () => {
        render(<CustomerForm />);
        expect(
            screen.getByRole('button', { name: /save draft/i }),
        ).toBeInTheDocument();
    });

    it('renders a Cancel link back to /admin/customers', () => {
        render(<CustomerForm />);
        expect(screen.getByRole('link', { name: /cancel/i })).toHaveAttribute(
            'href',
            '/admin/customers',
        );
    });
});

describe('Admin/Customers/Form — edit mode', () => {
    it('sets AdminLayout title to "Edit Customer" in edit mode', () => {
        render(<CustomerForm customer={EXISTING_CUSTOMER as any} />);
        expect(screen.getByTestId('admin-layout')).toHaveAttribute(
            'data-title',
            'Edit Customer',
        );
    });

    it('pre-fills the name input with the existing name', () => {
        render(<CustomerForm customer={EXISTING_CUSTOMER as any} />);
        expect(
            screen.getByPlaceholderText('e.g. Mwanga Microfinance'),
        ).toHaveValue('Mwanga Microfinance');
    });

    it('pre-fills the website input with the existing website', () => {
        render(<CustomerForm customer={EXISTING_CUSTOMER as any} />);
        expect(screen.getByPlaceholderText('https://example.org')).toHaveValue(
            'https://mwanga.example.org',
        );
    });

    it('shows "Update" submit button in edit mode when publish date is set', () => {
        render(<CustomerForm customer={EXISTING_CUSTOMER as any} />);
        expect(
            screen.getByRole('button', { name: /update/i }),
        ).toBeInTheDocument();
    });
});
