/* eslint-disable react-refresh/only-export-components */
import * as Sentry from '@sentry/react';
import { OverlayProvider } from 'overlay-kit';
import React, { lazy } from 'react';
import {
  createRoutesFromChildren,
  matchRoutes,
  Navigate,
  Route,
  Routes,
  useLocation,
  useNavigationType,
} from 'react-router';
import { createBrowserRouter } from 'react-router-dom';

import { AppChildren } from '@/app/app-children';
import { GlobalAPIErrorBoundary } from '@/widgets/error-boundaries';
import { NotFoundError } from '@/widgets/fallbacks';
import { ProtectedRoute } from '@/widgets/protected-route';
import { PullToRefreshRoute } from '@/widgets/pull-to-refresh/pull-to-refresh-route';
import { SubLayout } from '@/widgets/sub-layout';
import { IS_PROD } from '@/shared/constants/environment';
import { ROUTE_NAMES } from '@/shared/constants/route-names';
import { toCamelCase } from '@/shared/lib/to-camel-case';

export const initSentry = () => {
  if (IS_PROD) {
    Sentry.init({
      environment: import.meta.env.VITE_APP_ENV,
      dsn: 'https://ddd8755ce025f753e8521af5b1034a93@o4507569039867904.ingest.us.sentry.io/4507569041244160',
      integrations: [
        Sentry.browserTracingIntegration(),
        Sentry.browserProfilingIntegration(),
        Sentry.replayIntegration(),
        Sentry.reactRouterV6BrowserTracingIntegration({
          useEffect: React.useEffect,
          useLocation,
          useNavigationType,
          createRoutesFromChildren,
          matchRoutes,
        }),
      ],
      normalizeDepth: 6,
      // Performance Monitoring
      tracesSampleRate: 1.0, //  Capture 100% of the transactions
      // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
      tracePropagationTargets: [
        'http://3.35.79.250:8090'
      ],
      // Session Replay
      replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
      replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.

      profilesSampleRate: 1.0,
    });
  }
};

const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV6(createBrowserRouter);

const modules = import.meta.glob('~/pages/**/*.tsx');

const lazyLoad = (path: string) => {
  const module = modules[`${path}.tsx`];
  if (!module) {
    throw new Error(`Module not found: ${path}`);
  }

  const namedExportKebab = path.split('/').pop()?.replace('.tsx', '') as string;
  const namedExportCamel = toCamelCase(namedExportKebab);
  return lazy(() => module().then((load: any) => ({ 
    default: load[namedExportCamel] 
  })));
};

const HomePage                = lazyLoad('/src/pages/home/home-page'); 
const TransactionPages        = lazyLoad('/src/pages/transaction/transaction-pages');
const SettlementPages         = lazyLoad('/src/pages/settlement/settlement-pages');
const MerchantPages           = lazyLoad('/src/pages/merchant/merchant-pages');
const PaymentPages            = lazyLoad('/src/pages/payment/payment-pages');
const AccountPages            = lazyLoad('/src/pages/account/account-pages');
const VatReturnPages          = lazyLoad('/src/pages/vat-return/vat-return-pages');
const AdditionalServicePages  = lazyLoad('/src/pages/additional-service/additional-service-pages');
const SupportPages            = lazyLoad('/src/pages/support/support-pages');
const SettingPage             = lazyLoad('/src/pages/setting/setting-page'); 
const AlarmPages              = lazyLoad('/src/pages/alarm/alarm-pages');
const XkeypadPage             = lazyLoad('/src/pages/xkeypad/xkeypad-page');
const XkeypadSample           = lazyLoad('/src/pages/xkeypad/xkeypad-sample');
const TaxInvoicePages         = lazyLoad('/src/pages/tax-invoice/tax-invoice-pages');

export const SentryRoutes = Sentry.withSentryReactRouterV6Routing(Routes);
const Pages = () => {
  return (
    <OverlayProvider>
      <GlobalAPIErrorBoundary>
        <AppChildren />
        <SentryRoutes>
          <Route element={<SubLayout />}>
            <Route element={<ProtectedRoute />}>
              <Route path={ROUTE_NAMES.home} element={<HomePage />} />
              <Route path={ROUTE_NAMES.transaction.base} element={<TransactionPages />} />
              <Route path={ROUTE_NAMES.settlement.base} element={<SettlementPages />} />
              <Route path={ROUTE_NAMES.merchant.base} element={<MerchantPages />} />
              <Route path={ROUTE_NAMES.payment.base} element={<PaymentPages />} />
              <Route path={ROUTE_NAMES.account.base} element={<AccountPages />} />
              <Route path={ROUTE_NAMES.vatReturn.base} element={<VatReturnPages />} />
              <Route path={ROUTE_NAMES.additionalService.base} element={<AdditionalServicePages />} />
              <Route path={ROUTE_NAMES.support.base} element={<SupportPages />} />
              <Route path={ROUTE_NAMES.setting} element={<SettingPage />} />
              <Route path={ROUTE_NAMES.alarm.base} element={<AlarmPages />} />
              <Route path={ROUTE_NAMES.xkeypad} element={<XkeypadPage />} />
              <Route path={ROUTE_NAMES.xkeypadSample} element={<XkeypadSample />} />
              <Route path={ROUTE_NAMES.taxInvoice.base} element={<TaxInvoicePages />} />
            </Route>
            <Route path="*" element={<NotFoundError />} />
          </Route>
          <Route element={<PullToRefreshRoute />}>
            <Route element={<ProtectedRoute />}>
              
              
            </Route>
          </Route>
        </SentryRoutes>
      </GlobalAPIErrorBoundary>
    </OverlayProvider>
  );
};

export const router = sentryCreateBrowserRouter([
  {
    path: '/',
    element: <Navigate to={ROUTE_NAMES.home} />,
  },
  {
    path: '/*',
    element: <Pages />,
  },
]);
