import React from 'react'

import { MenuItem, MenuItemGroupItem, MenuItemType } from '@komi-app/creator-ui'
import { useTypedSelector } from 'redux/rootReducer'

import { selectUserData } from 'redux/User/selector'
import { FLAGS, getFeatureValue, useFeatureIsOn } from '@komi-app/flags-sdk'
import { conditionalInclude } from 'utils/operators'

import config from 'config'

import { ReactComponent as SpaceDashboardInvertedOutlinedIcon } from 'icons/dashboard-inverted.svg'
import { ReactComponent as MonetizationIcon } from 'icons/dollar-in-circle.svg'
import {
  MdOutlineCampaign as CampaignOutlinedIcon,
  MdOutlinePeopleAlt as PeopleAltOutlinedIcon,
  MdOutlineSpaceDashboard as SpaceDashboardOutlinedIcon,
  MdLeaderboard as LeaderboardIcon,
  MdOutlineRecordVoiceOver as RecordVoiceOverOutlinedIcon,
  MdOutlineSettings as SettingsOutlinedIcon
} from 'react-icons/md'
import { ROLE } from '../redux/User/types'
import { useUpcomingAdjustment } from '../utils/upcoming'
import { useHasRole, useIsOwner } from './user-hooks'
import { useAudienceAndCampaignFeatureOn } from './useAudienceAndCampaignMobileBlock'
import { useHasSMS } from './user-hooks/useHasSMS'

export function useNavMenu(): MenuItem[] {
  const isEdcmFlagOn = useFeatureIsOn(FLAGS.FEAT_CAC_305_EDCM)
  const user = useTypedSelector(selectUserData)
  const isSsxUser = useHasRole(ROLE.SelfSign)

  const useTiers = useAudienceAndCampaignFeatureOn(FLAGS.USE_TIERS_TALENT)
  const isDcaSettingsFlagOn =
    useAudienceAndCampaignFeatureOn(FLAGS.DCA) || useTiers

  const hasSMS = useHasSMS()

  const isReferralProgramOn = useFeatureIsOn(FLAGS.FEAT_CELLO_REFERRAL)
  const isCelloMenuEnabled = useFeatureIsOn(FLAGS.FEAT_CELLO_NAV_MENU)

  const referalButtonProps = getFeatureValue(
    FLAGS.FEAT_SB_1794_NAV_REFERRAL_BUTTON_PROPS,
    {
      variant: 'default',
      label: 'Refer a Friend'
    }
  )

  const isContentMenuEnabled = useFeatureIsOn(FLAGS.FEAT_SB_389_ADD_ITEM_MENU)
  const isNavbarCopyUpdateEnabled = useFeatureIsOn(FLAGS.NAVBAR_COPY_UPDATE)

  const isMonetizationPageEnabled = useFeatureIsOn(FLAGS.USE_MONETIZATION_PAGE)

  const settingsMenuItem = useSettingsMenuItem()

  const isAnalyticsHidden = useFeatureIsOn(
    FLAGS.FEAT_HIDE_ANALYTICS_FOR_SOME_USERS
  )

  const isRestrictedDCMForSSXOn = useFeatureIsOn(
    FLAGS.FEAT_SB_627_SSX_RESTRICTED_DCM
  )
  const talentProfile = user?.talentProfile
  const handle =
    talentProfile?.user?.username || (talentProfile as any)?.username

  const isRoot = location.host === config.service.domain

  if (!(handle || !isRoot)) {
    return []
  }

  const maybeAudienceAndCampaigns: MenuItem[] = isDcaSettingsFlagOn
    ? [
        {
          name: getAudienceAndCampaignsTitle(isNavbarCopyUpdateEnabled, hasSMS),
          icon: isNavbarCopyUpdateEnabled ? (
            <CampaignOutlinedIcon
              size={24}
              data-testid="CampaignOutlinedIcon"
            />
          ) : (
            <PeopleAltOutlinedIcon
              size={24}
              data-testid="PeopleAltOutlinedIcon"
            />
          ),
          type: MenuItemType.GROUP,
          items: [
            {
              name: 'Contacts',
              type: MenuItemType.LINK,
              url: '/admin/audience-campaigns/contacts'
            },
            {
              name: 'Segments',
              type: MenuItemType.LINK,
              url: '/admin/audience-campaigns/segments'
            },
            {
              name: 'Campaigns',
              type: MenuItemType.LINK,
              url: '/admin/audience-campaigns/campaigns'
            },
            {
              name: 'Templates',
              type: MenuItemType.LINK,
              url: '/admin/audience-campaigns/templates'
            },
            ...conditionalInclude(isEdcmFlagOn, {
              name: 'Website embed',
              type: MenuItemType.LINK as const,
              url: '/admin/audience-campaigns/embed'
            })
          ]
        }
      ]
    : []

  const maybeAudienceManager: MenuItem[] =
    !isDcaSettingsFlagOn && isRestrictedDCMForSSXOn
      ? [
          {
            name: isNavbarCopyUpdateEnabled
              ? hasSMS
                ? 'Email & SMS'
                : 'Email Marketing'
              : 'Audience Manager',
            icon: isNavbarCopyUpdateEnabled ? (
              <CampaignOutlinedIcon
                size={24}
                data-testid="CampaignOutlinedIcon"
              />
            ) : (
              <PeopleAltOutlinedIcon
                size={24}
                data-testid="PeopleAltOutlinedIcon"
              />
            ),
            type: MenuItemType.GROUP,
            items: [
              {
                name: 'Contacts',
                type: MenuItemType.LINK,
                url: '/admin/audience-campaigns/contacts'
              }
            ]
          }
        ]
      : []

  const analyticsMenuItem: MenuItem = isDcaSettingsFlagOn
    ? {
        name: 'Analytics',
        icon: <LeaderboardIcon size={24} data-testid="LeaderboardIcon" />,
        type: MenuItemType.LINK,
        url: '/admin/analytics'
      }
    : {
        name: 'Data & Analytics',
        icon: <LeaderboardIcon size={24} data-testid="LeaderboardIcon" />,
        type: MenuItemType.GROUP,
        items: [
          {
            name: 'Analytics',
            type: MenuItemType.LINK,
            url: '/admin/analytics'
          },
          {
            name: 'Data Export',
            type: MenuItemType.LINK,
            url: '/admin/data-export'
          }
        ]
      }
  const maybeAnalyticsMenuItem: MenuItem[] = isAnalyticsHidden
    ? []
    : [analyticsMenuItem]

  const profileBuilderItems: MenuItemGroupItem[] = [
    {
      name: isContentMenuEnabled ? 'Content' : 'Modules',
      type: MenuItemType.LINK,
      url: '/admin/modules'
    },
    { name: 'Header', type: MenuItemType.LINK, url: '/admin/header' },
    {
      name: 'Social Links',
      type: MenuItemType.LINK,
      url: '/admin/social-links'
    },
    { name: 'Theme', type: MenuItemType.LINK, url: '/admin/theme' }
  ]

  const referralMenuItem: MenuItem = {
    name: referalButtonProps?.label,
    icon: (
      <RecordVoiceOverOutlinedIcon
        size={24}
        data-testid="RecordVoiceOverOutlinedIcon"
      />
    ),
    type: MenuItemType.LINK,
    key: 'cello',
    url: '#',
    semantic: referalButtonProps.variant
  }

  const monetizationMenuItem: MenuItem[] =
    isSsxUser && isMonetizationPageEnabled
      ? [
          {
            name: 'Monetization',
            icon: <MonetizationIcon />,
            type: MenuItemType.LINK,
            url: '/admin/monetization'
          }
        ]
      : []

  const maybeReferralMenuItem: MenuItem[] =
    isReferralProgramOn && isCelloMenuEnabled ? [referralMenuItem] : []

  return [
    {
      name: isNavbarCopyUpdateEnabled ? 'Mini Site' : 'Profile Builder',
      icon: isNavbarCopyUpdateEnabled ? (
        <SpaceDashboardInvertedOutlinedIcon data-testid="SpaceDashboardInvertedOutlinedIcon" />
      ) : (
        <SpaceDashboardOutlinedIcon
          size={24}
          data-testid="SpaceDashboardOutlinedIcon"
        />
      ),
      type: MenuItemType.GROUP,
      items: profileBuilderItems
    },
    ...monetizationMenuItem,
    ...maybeAudienceAndCampaigns,
    ...maybeAudienceManager,
    ...maybeAnalyticsMenuItem,
    settingsMenuItem,
    ...maybeReferralMenuItem
  ]
}

function useSettingsMenuItem(): MenuItem {
  const isSelfSign = useHasRole(ROLE.SelfSign)
  const useTiers = useAudienceAndCampaignFeatureOn(FLAGS.USE_TIERS_TALENT)
  const isNavbarCopyUpdateEnabled = useFeatureIsOn(FLAGS.NAVBAR_COPY_UPDATE)

  const hasSMS = useHasSMS()

  const isAudiencesAndCampaignSettingsEnabled =
    useAudienceAndCampaignFeatureOn(FLAGS.DCA) || useTiers
  const upcomingAdjustment = useUpcomingAdjustment()
  const isOwner = useIsOwner()

  const isBetaSubscriptionEnabled = useFeatureIsOn(FLAGS.BETA_SUBSCRIPTION)

  const isAffiliateLinksEnabled = useFeatureIsOn(
    FLAGS.SB_789_ENABLE_AFFILIATE_SCHEME
  )

  return {
    name: 'Settings',
    icon: <SettingsOutlinedIcon size={24} data-testid="SettingsOutlinedIcon" />,
    type: MenuItemType.GROUP,
    items: [
      {
        name: isNavbarCopyUpdateEnabled ? 'Mini Site' : 'Profile Information',
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/profile-information')
      },
      ...conditionalInclude(isAudiencesAndCampaignSettingsEnabled, {
        name: getAudienceAndCampaignsTitle(isNavbarCopyUpdateEnabled, hasSMS),
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/audiences-and-campaigns')
      }),
      // This is for a small number of beta users who pay their subscription through Stripe
      ...conditionalInclude(isBetaSubscriptionEnabled, {
        name: 'Billing & Subscription',
        type: MenuItemType.LINK,
        external: true,
        url: 'https://billing.stripe.com/p/login/00gg2649xfmLbdK3cc'
      }),
      ...conditionalInclude(isOwner && isSelfSign, {
        name: isAffiliateLinksEnabled ? 'Billing & Payments' : 'Subscription',
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/subscription')
      }),
      {
        name: 'Team Members',
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/team-members')
      },
      {
        name: 'Integrations',
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/integrations')
      },
      {
        name: 'Advanced Settings',
        type: MenuItemType.LINK,
        url: upcomingAdjustment('/advanced-settings')
      }
    ]
  }
}

function getAudienceAndCampaignsTitle(
  isNavbarCopyUpdateEnabled: boolean,
  hasSMS: boolean
) {
  if (isNavbarCopyUpdateEnabled) {
    if (hasSMS) {
      return 'Email & SMS'
    }

    return 'Email Marketing'
  }

  return 'Audiences & Campaigns'
}

export default useNavMenu
