import React, { lazy, useEffect, useState } from 'react'
import { Redirect, Switch } from 'react-router-dom'

import {
  dcaBaseUrl,
  dcaTollFreeRegisterUrl,
  dcaTollFreeSearchUrl,
  campaignCreateScheduleUrl,
  dcaSystemTemplatesUrl
} from 'constants/dca'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'

import ExpertTerms from '../pages/ExpertTerms'
import LogoutPage from 'pages/Logout'
import PreviewLayout from 'layout/PreviewLayout'
import EmptyLayout from 'layout/EmptyLayout'
import MainLayout from 'layout/MainLayout'
import EmptyWithLogoLayout from '../layout/EmptyWithLogoLayout'
import SendLoginLinkEmailModal from '../components/SendLoginLinkEmailModal'
import OnboardingLayout from '../layout/OnboardingLayout'
import OnboardingFlow from '../pages/onboarding/OnboardingFlow'
import EmptyOnboardingLayout from '../layout/EmptyOnboardingLayout'
import EmptyLayoutWithSidebar from 'layout/EmptyLayoutWithSidebar'
import SMSCampaignPage from '../pages/AudienceAndCampaigns/Pages/Campaigns/SMSCampaignPage/SMSCampaignPage'
import CustomTagsReviewPage from 'pages/AudienceAndCampaigns/Pages/CustomTags/CustomTagsReviewPage/CustomTagsReviewPage'
import TollFreeSearch from 'components/ProfileSettings/AudiencesAndCampaigns/SMSSetup/TollFreeSearch/TollFreeSearch'
import TollFreeRegisterPage from 'components/ProfileSettings/AudiencesAndCampaigns/SMSSetup/TollFreeRegister/TollFreeRegister'
import SystemTemplates from 'pages/AudienceAndCampaigns/Pages/Templates/SystemTemplates'
import EmailCampaignSchedulePage from 'pages/AudienceAndCampaigns/Pages/Campaigns/EmailCampaign/EmailCampaignSchedule/EmailCampaignSchedule'
import { EmailCampaignReport } from 'pages/AudienceAndCampaigns/Pages/Campaigns/EmailCampaign/EmailCampaignReport/EmailCampaignReport'
import { StripeRefreshUrl } from 'components/ProfileSettings/StripeRefreshUrl'
import { useDigitalProductFeatures } from 'hooks/useDigitalProductFeatures'
import { ROLE } from 'redux/User/types'
import { ProtectedRoute, PublicRoute } from 'components/Router'
import { useUserAccountDetails } from '../hooks/useUserAccountDetails'
import { minutesFromNow } from 'utils'
import Loading from 'components/Loading'

const Profile = lazy(() => import('pages/Profile'))
const ContentMenuPage = lazy(() => import('pages/Profile/ContentMenuPage'))
const FreeDownloadPage = lazy(() => import('pages/Profile/AddFreeDownload'))
const PaidDownloadPage = lazy(() => import('pages/Profile/AddPaidDownload'))
const DigitalProductForm = lazy(() => import('pages/Profile/DigitalProduct'))
const ShortVideoPage = lazy(() => import('pages/Profile/AddShortVideo'))
const TemplatesPage = lazy(() => import('pages/Profile/TemplatesPage'))
const Analytics = lazy(() => import('pages/Analytics'))
const AsqMePage = lazy(() => import('pages/Profile/AsqMePage'))
const DataExport = lazy(() => import('pages/DataExport'))
const Monetization = lazy(() => import('pages/Monetization'))
const Home = lazy(() => import('pages/Home'))
const ErrorPage = lazy(() => import('pages/ErrorPage'))
const UnauthorizedPage = lazy(() => import('pages/UnauthorizedPage'))
const NotfoundPage = lazy(() => import('pages/NotFoundPage'))
const BecomeATalent = lazy(() => import('pages/BecomeATalent'))
const AuthCronofy = lazy(() => import('pages/AuthCronofy'))
const AuthShopify = lazy(() => import('pages/AuthShopify'))
const SwitchToTalent = lazy(() => import('pages/SwitchToTalent'))
const BecomeATalentRedirect = lazy(() => import('pages/BecomeATalentRedirect'))

const AccountSettings = lazy(
  () => import('pages/AccountSetting/AccountSettingNew')
)
const AccountSettingSubscription = lazy(
  () => import('pages/AccountSetting/Subscription')
)
const Integrations = lazy(
  () => import('components/ProfileSettings/Integrations')
)

const UserSettingContainer = lazy(() => import('pages/UserSetting/UserSetting'))
const AudienceCampaigns = lazy(
  () => import('pages/AudienceAndCampaigns/Settings')
)
const TeamMembers = lazy(
  () => import('../components/ProfileSettings/TeamMembers/TeamMembers')
)

export function adminRoute(path: string) {
  return `/admin${path}`
}

export enum MENU_LINKS {
  ANALYTICS = '/analytics',
  DATA_CAPTURE_FORM = '/data-capture-form', //Legacy
  DATA_EXPORT = '/data-export',
  ACCOUNT_SETTINGS = '/account-setting',
  PROFILE_SETTINGS = '/user/settings',
  TEAM_MEMBERS = '/team-member',
  FAQ = '/faq',
  CONTACT_US = '/contact',
  LOGOUT = '/logout',
  SETUP_PROFILE = '/setup-profile',
  AUDIENCE_CAMPAIGNS = '/audience-campaigns'
}

const Routes = () => {
  const user = useUserAccountDetails()
  const [isNewUser, setIsNewUser] = useState<boolean | undefined>()

  // This flag should be evaluated properly on mobile - we want A&C pages to be accessible directly still. See useAudienceAndCampaignMobileBlock.ts
  const useTiers = useFeatureIsOn(FLAGS.USE_TIERS_TALENT)
  const isDcaShowSettingsOn = useFeatureIsOn(FLAGS.DCA) || useTiers
  const isMobileOnboardingExperimentEnabled = useFeatureIsOn(
    FLAGS.MOBILE_ONBOARDING_EXPERIMENT
  )
  const isOnboardingSocialLinksPageEnabled = useFeatureIsOn(
    FLAGS.FEAT_GS_162_ONBOARDING_SOCIAL_LINKS_PAGE
  )
  const isContentMenuEnabled = useFeatureIsOn(FLAGS.FEAT_SB_389_ADD_ITEM_MENU)
  const isTemplateV2Enabled = useFeatureIsOn(FLAGS.FEAT_SB_447_MODULE_TEMPLATES)

  const isRestrictedDCMForSSXOn = useFeatureIsOn(
    FLAGS.FEAT_SB_627_SSX_RESTRICTED_DCM
  )

  const isSmartScheduleCampaignsEnabled = useFeatureIsOn(
    FLAGS.SMART_SCHEDULE_TALENT
  )
  const isProcurementAvailable = useFeatureIsOn(
    FLAGS.FEAT_CRM_1241_PHONE_NUMBER_PROCUREMENT
  )
  const isTollFreeRegistrationAllowed = useFeatureIsOn(
    FLAGS.FEAT_CRM_1244_TOLL_FREE_REGISTRATION
  )

  const isSystemTemplatesVisible = useFeatureIsOn(
    FLAGS.FEAT_CRM_1284_SYSTEM_TEMPLATES
  )

  const { isFreeDownloadOn, isPaidDownloadOn, useNewForms } =
    useDigitalProductFeatures()

  const isShortVideoAutomationOn = useFeatureIsOn(FLAGS.SHORT_VIDEO_AUTOMATION)
  const isCreatorAnalyticsOn = useFeatureIsOn(FLAGS.CREATOR_ANALYTICS_CORE)
  const isCustomTagsEnabled = useFeatureIsOn(FLAGS.FEAT_CRM_CUSTOM_TAGS_IMPORT)
  const isUseMonetizationPage = useFeatureIsOn(FLAGS.USE_MONETIZATION_PAGE)

  useEffect(() => {
    if (user && user?.createdAt) {
      const minutesDifference = minutesFromNow(user.createdAt)

      if (minutesDifference > 2) {
        setIsNewUser(false)
      } else {
        setIsNewUser(true)
      }
    } else if (user) {
      setIsNewUser(false)
    }
  }, [user])

  const shouldRedirectToMonetization = isUseMonetizationPage && isNewUser

  const profilePaths = [
    '/admin/header',
    '/admin/theme',
    '/admin/social-links',
    '/admin/modules'
  ]

  if (user === undefined || isNewUser === undefined) {
    return <Loading />
  }

  return (
    <Switch>
      <Redirect
        from="/admin"
        to={adminRoute(
          `${shouldRedirectToMonetization ? '/monetization' : '/modules'}`
        )}
        exact
      />

      <ProtectedRoute
        exact
        path={[
          '/admin/audience-campaigns/sms-campaign-create',
          '/admin/audience-campaigns/sms-campaign-edit'
        ]}
        layout={EmptyLayoutWithSidebar}
        showSidebar
        component={SMSCampaignPage}
      />

      {isUseMonetizationPage && (
        <ProtectedRoute
          exact
          allowedRoles={ROLE.SelfSign}
          path="/admin/monetization"
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={Monetization}
        />
      )}

      {isSmartScheduleCampaignsEnabled && (
        <ProtectedRoute
          exact
          path={['/admin/audience-campaigns/email-campaign-report']}
          layout={EmptyLayoutWithSidebar}
          className="background-lowest"
          showSidebar
          component={EmailCampaignReport}
        />
      )}

      {isSmartScheduleCampaignsEnabled && (
        <ProtectedRoute
          exact
          path={[campaignCreateScheduleUrl]}
          layout={EmptyLayoutWithSidebar}
          className="background-lowest"
          showSidebar
          component={EmailCampaignSchedulePage}
        />
      )}

      {isCustomTagsEnabled && (
        <ProtectedRoute
          exact
          path={'/admin/audience-campaigns/custom-tags-review'}
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={CustomTagsReviewPage}
        />
      )}

      {isContentMenuEnabled && (
        <ProtectedRoute
          path="/admin/modules/new"
          component={ContentMenuPage}
          layout={MainLayout}
        />
      )}

      {useNewForms && (
        <ProtectedRoute
          path={[
            '/admin/modules/digital-product',
            '/admin/modules/digital-product/edit'
          ]}
          component={DigitalProductForm}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {!useNewForms && isFreeDownloadOn && (
        <ProtectedRoute
          path="/admin/modules/free-download"
          component={FreeDownloadPage}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {!useNewForms && (
        <ProtectedRoute
          path="/admin/modules/free-download/edit"
          component={FreeDownloadPage}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {!useNewForms && isPaidDownloadOn && (
        <ProtectedRoute
          path="/admin/modules/digital-product"
          component={PaidDownloadPage}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {!useNewForms && (
        <ProtectedRoute
          path="/admin/modules/digital-product/edit"
          component={PaidDownloadPage}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {isShortVideoAutomationOn && (
        <ProtectedRoute
          path={[
            '/admin/modules/tiktok',
            '/admin/modules/tiktok/manual',
            '/admin/modules/tiktok/automatic',
            '/admin/modules/tiktok/automatic/edit',
            '/admin/modules/reels',
            '/admin/modules/reels/manual',
            '/admin/modules/reels/automatic',
            '/admin/modules/reels/automatic/edit'
          ]}
          exact
          component={ShortVideoPage}
          layout={EmptyLayoutWithSidebar}
        />
      )}

      {isTemplateV2Enabled && (
        <ProtectedRoute
          path="/admin/modules/templates"
          component={TemplatesPage}
          layout={MainLayout}
        />
      )}

      <ProtectedRoute
        path={[
          '/admin/modules/asqme-q-and-a',
          '/admin/modules/asqme-paid-dm',
          '/admin/modules/asqme-video-request',
          '/admin/modules/asqme-file-request'
        ]}
        component={AsqMePage}
        layout={EmptyLayoutWithSidebar}
      />

      <ProtectedRoute
        exact
        path={profilePaths}
        layout={PreviewLayout}
        showSidebar
        component={Profile}
      />

      {isMobileOnboardingExperimentEnabled && (
        <ProtectedRoute
          exact
          path="/admin/send-login-link"
          layout={EmptyWithLogoLayout}
          showSidebar
          component={SendLoginLinkEmailModal}
        />
      )}

      {isOnboardingSocialLinksPageEnabled && (
        <ProtectedRoute
          exact
          path={[
            '/admin/onboarding/social-links',
            '/admin/onboarding/header-image'
          ]}
          layout={OnboardingLayout}
          showSidebar
          component={OnboardingFlow}
        />
      )}

      {isOnboardingSocialLinksPageEnabled && (
        <ProtectedRoute
          exact
          path={['/admin/onboarding/complete']}
          layout={EmptyOnboardingLayout}
          showSidebar
          component={OnboardingFlow}
        />
      )}

      <ProtectedRoute
        exact
        path="/home"
        layout={MainLayout}
        showSidebar
        component={Home}
      />
      <ProtectedRoute
        exact
        path="/logout"
        layout={MainLayout}
        showSidebar
        component={LogoutPage}
      />
      <ProtectedRoute
        exact
        path={adminRoute('/team-member')}
        layout={PreviewLayout}
        showSidebar
        component={TeamMembers}
        className="preview-layout--additional-page preview-layout--additional-page-team-member"
      />
      <ProtectedRoute
        showSidebar
        exact
        path={adminRoute('/settings')}
        layout={MainLayout}
        component={() => (
          <Redirect to={adminRoute('/settings/profile-information')} />
        )}
      />
      <ProtectedRoute
        exact
        path={adminRoute('/settings/subscription/:step')}
        layout={MainLayout}
        component={AccountSettingSubscription}
        className="preview-layout--additional-page preview-layout--additional-page-account-setting"
      />
      {isShortVideoAutomationOn && (
        <ProtectedRoute
          exact
          path={adminRoute('/settings/integrations')}
          component={Integrations}
          layout={EmptyLayoutWithSidebar}
        />
      )}
      <ProtectedRoute
        exact
        path={adminRoute('/settings/:section')}
        layout={PreviewLayout}
        showSidebar
        component={AccountSettings}
        className="preview-layout--additional-page preview-layout--additional-page-account-setting"
      />
      {isSystemTemplatesVisible && (
        <ProtectedRoute
          exact
          path={[dcaSystemTemplatesUrl]}
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={SystemTemplates}
        />
      )}

      {isPaidDownloadOn && (
        <ProtectedRoute
          exact
          path={adminRoute('/settings/subscription/stripe/refresh-url')}
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={StripeRefreshUrl}
        />
      )}

      {isProcurementAvailable && (
        <ProtectedRoute
          exact
          path={[dcaTollFreeSearchUrl]}
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={TollFreeSearch}
        />
      )}
      {isTollFreeRegistrationAllowed && (
        <ProtectedRoute
          exact
          path={[dcaTollFreeRegisterUrl]}
          layout={EmptyLayoutWithSidebar}
          showSidebar
          component={TollFreeRegisterPage}
        />
      )}

      <ProtectedRoute
        exact
        path={adminRoute('/analytics')}
        layout={isCreatorAnalyticsOn ? EmptyLayoutWithSidebar : PreviewLayout}
        showSidebar
        component={Analytics}
        className="preview-layout--additional-page"
      />

      {/**
       * Route for Data export which appears under the 'Data & Analytics' tab
       * Contains 2 views: Data Capture Forms (prev it's own page) + Pre Release Export
       **/}
      <ProtectedRoute
        exact
        path={adminRoute('/data-export')}
        layout={PreviewLayout}
        showSidebar
        component={DataExport}
        className="preview-layout--additional-page preview-layout--additional-page-fan-club"
      />

      <PublicRoute
        path="/switch-to-talent"
        showSidebar
        layout={PreviewLayout}
        component={SwitchToTalent}
      />

      <PublicRoute
        path="/expert-terms"
        layout={EmptyLayout}
        component={ExpertTerms}
      />
      <PublicRoute
        path="/redirect-become-a-talent"
        layout={EmptyLayout}
        component={BecomeATalentRedirect}
      />
      <PublicRoute
        path="/become-a-talent"
        layout={EmptyLayout}
        component={BecomeATalent}
      />

      <ProtectedRoute
        path="/auth/cronofy"
        component={AuthCronofy}
        layout={EmptyLayout}
      />
      <ProtectedRoute
        path="/auth/shopify"
        component={AuthShopify}
        layout={EmptyLayout}
      />
      <PublicRoute path="/errors" component={ErrorPage} layout={EmptyLayout} />
      <PublicRoute
        path="/401"
        component={UnauthorizedPage}
        layout={EmptyLayout}
      />

      <ProtectedRoute
        exact
        path="/me"
        layout={MainLayout}
        showSidebar
        component={UserSettingContainer}
        className="preview-layout--additional-page preview-layout--additional-page-account-setting"
      />

      <PublicRoute
        path={adminRoute('/redirect-become-a-talent')}
        layout={EmptyLayout}
        component={BecomeATalentRedirect}
      />
      <ProtectedRoute
        path={adminRoute('/auth/shopify')}
        component={AuthShopify}
        layout={EmptyLayout}
      />

      {isDcaShowSettingsOn && (
        <ProtectedRoute
          exact
          path={`${dcaBaseUrl}`}
          layout={PreviewLayout}
          showSidebar
          component={() => <Redirect to={`${dcaBaseUrl}/contacts`} />}
          className="preview-layout--additional-page"
        />
      )}

      {isDcaShowSettingsOn && (
        <ProtectedRoute
          exact
          path={`${dcaBaseUrl}/:section`}
          layout={PreviewLayout}
          showSidebar
          component={AudienceCampaigns}
          className="preview-layout--additional-page preview-layout--additional-page-account-setting"
        />
      )}

      {!isDcaShowSettingsOn && isRestrictedDCMForSSXOn && (
        <ProtectedRoute
          exact
          path={dcaBaseUrl}
          layout={PreviewLayout}
          showSidebar
          component={() => <Redirect to={`${dcaBaseUrl}/contacts`} />}
          className="preview-layout--additional-page"
        />
      )}

      {!isDcaShowSettingsOn && isRestrictedDCMForSSXOn && (
        <ProtectedRoute
          exact
          path={`${dcaBaseUrl}/contacts`}
          layout={PreviewLayout}
          showSidebar
          component={AudienceCampaigns}
          className="preview-layout--additional-page preview-layout--additional-page-account-setting"
        />
      )}

      {!isDcaShowSettingsOn && !isRestrictedDCMForSSXOn && (
        // Adds a loading page here as it takes time for the flag to compute
        <ProtectedRoute
          path={`${dcaBaseUrl}`}
          layout={PreviewLayout}
          showSidebar
          component={() => <></>}
          className="preview-layout--additional-page"
        />
      )}

      <PublicRoute path="*" component={NotfoundPage} layout={EmptyLayout} />
    </Switch>
  )
}

export default React.memo(Routes)
