/**
 * Sentry must be initialized before any other app code.
 */
import { initSentry } from './shared/sentry';
import { ErrorBoundary } from '@sentry/react';

/**
 * External dependencies
 */
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
import { lazy, Suspense } from '@wordpress/element';

/**
 * Internal dependencies
 */
import './index.scss';
import LandingPage from './pages/LandingPage';
import { useNavigation } from './shared/hooks';
import { AuthProvider } from './shared/context';

initSentry();

const LazyPreviousShipmentsPage = lazy(() => import('./pages/PreviousShipmentsPage'));
const LazyOrderShipPage = lazy(()=> import('./pages/OrderShipPage'))
const LazySettingsPage = lazy(()=>import('./pages/SettingsPage'))

const PreviousShipmentsPageWrapper = () => (
	<AuthProvider>
		<Suspense fallback={<div style={{ padding: 24, textAlign: 'center' }}>Loading...</div>}>
			<LazyPreviousShipmentsPage />
		</Suspense>
	</AuthProvider>
);

const SettingsPageWrapper = () => (
	<AuthProvider>
		<Suspense fallback={<div style={{ padding: 24, textAlign: 'center' }}>Loading...</div>}>
			<LazySettingsPage />
		</Suspense>
	</AuthProvider>
);

const Parcel2GoShipping = () => {
	const { selectedOrderId, handleShipNow, handleBack } = useNavigation();

	if (selectedOrderId !== null) {
		return (
			<LazyOrderShipPage
				orderId={selectedOrderId}
				onBack={handleBack}
			/>
		);
	}

	return <LandingPage onShipNow={handleShipNow} />;
};

const Parcel2GoShippingWithErrorBoundary = () => (
	<AuthProvider>
		<ErrorBoundary
			fallback={({ error }) => (
				<div style={{ padding: 24 }}>
					<p><strong>{__('Something went wrong.', 'parcel2go-shipping')}</strong></p>
					<p>{error instanceof Error ? error.message : String(error ?? '')}</p>
				</div>
			)}
		>
			<Parcel2GoShipping />
		</ErrorBoundary>
	</AuthProvider>
);

addFilter(
	'woocommerce_admin_pages_list',
	'parcel2go-shipping',
	(pages: any[]) => {
		pages.push(
			{
				container: Parcel2GoShippingWithErrorBoundary,
				path: '/parcel2go-shipping',
				breadcrumbs: [__('Parcel2Go Shipping', 'parcel2go-shipping')],
				navArgs: {
					id: 'parcel2go_shipping',
				},
			},
			{
				container: PreviousShipmentsPageWrapper,
				path: '/parcel2go-shipping/shipments',
				parent: 'parcel2go_shipping-landing-page',
				breadcrumbs: [
					__('Parcel2Go Shipping', 'parcel2go-shipping'),
					__('Previous shipping labels', 'parcel2go-shipping'),
				],
				navArgs: {
					id: 'parcel2go_shipping_shipments',
				},
			},
			{
				container: SettingsPageWrapper,
				path: '/parcel2go-shipping/settings',
				parent: 'parcel2go_shipping-landing-page',
				breadcrumbs: [
					__('Parcel2Go Shipping', 'parcel2go-shipping'),
					__('Settings', 'parcel2go-shipping'),
				],
				navArgs: {
					id: 'parcel2go_shipping_settings',
				},
			}
		);

		return pages;
	}
);
