import React from 'react'
import './SubscriptionBanner.scss'
import notification from 'utils/notification'

import { useHistory } from 'react-router'
import { getSubscriptionOverviewData } from 'utils/subscription'
import { HeaderMessage } from '@komi-app/components'
import { SEGMENT_EVENTS } from 'constants/segment'
import { useUserAgentContext } from 'context/user-agent'
import { useAnalytics } from 'hooks/useAnalytics'
import { OverviewStatus } from 'types/sales'
import { useTypedSelector } from 'redux/rootReducer'
import {
  selectProfileBuilderSubscription,
  selectUserData
} from 'redux/User/selector'
import { hasOwnership } from 'utils/user'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useWindowSize } from 'hooks'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'

export type InlineMessageType = 'info' | 'warning' | 'error'

export interface SubscriptionBannerProps {
  messageText: string
  level: InlineMessageType
  closeable: boolean
  setBannerDisplayed: (value: boolean) => void
}

const SubscriptionBanner = ({
  messageText,
  level,
  closeable,
  setBannerDisplayed
}: SubscriptionBannerProps) => {
  const history = useHistory()
  const uri =
    process.env.REACT_APP_TRIAL_BANNER_CTA ||
    '/admin/settings/subscription/select-plan'
  const { sendSegmentEvent } = useAnalytics()
  const ua = useUserAgentContext()
  const subscription = useTypedSelector(selectProfileBuilderSubscription)

  //For beta users we redirect the subscription to stripe for payment
  const isBetaBannerOn =
    useFeatureIsOn(FLAGS.BETA_SUBSCRIPTION_BANNER) ||
    useFeatureIsOn(FLAGS.BETA_TRIAL_EXPIRED_BANNER) ||
    useFeatureIsOn(FLAGS.BETA_SUBSCRIPTION_EXTENSION_BANNER)
  const stripeCheckoutUri = 'https://buy.stripe.com/8wMcOM0NDfNR9MIeUU'

  const { width } = useWindowSize()
  const isMobile = width && width <= 768
  const isShortTrialMessageOn =
    useFeatureIsOn(FLAGS.FEAT_SB_354_SHORT_TRIAL_MESSAGE) && !!isMobile

  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const clickSubscribe = createTracker(CreatorEvent.CLICK_SUBSCRIBE)
  // check if user is owner of talentProfile
  const talent = useTypedSelector(selectUserData)

  const onClick = () => {
    if (isBetaBannerOn) {
      window.open(stripeCheckoutUri, '_blank')
    } else {
      const { trialRemainingDays, status: overviewStatus } =
        getSubscriptionOverviewData(subscription)

      const status = overviewStatus
        ? {
            [OverviewStatus.ACTIVE]: 'Is subscribed' as const,
            [OverviewStatus.FREE_TRIAL]: 'On trial' as const,
            [OverviewStatus.FREE_TRIAL_EXPIRED]: 'Trial expired' as const,
            [OverviewStatus.CANCELLED]: 'Cancelled' as const,
            [OverviewStatus.INACTIVE]: 'Inactive' as const,
            [OverviewStatus.OVERDUE]: 'Overdue' as const
          }[overviewStatus]
        : undefined

      const from = 'Profile editor'
      const method = 'Self Sign Up'
      const remaining = trialRemainingDays

      useAnalyticsSDK
        ? clickSubscribe({
            from,
            method,
            remaining,
            status
          })
        : sendSegmentEvent(SEGMENT_EVENTS.CLICK_SUBSCRIBE, {
            'Button placement': from,
            'Free trial days remaining': remaining,
            'Operating System': ua.os.name,
            'Profile Creation Method': method,
            'Subscription status': status
          })
      hasOwnership(talent)
        ? history.push(uri)
        : notification.error({
            message:
              ' Sorry, subscriptions can only be managed by the account holder'
          })
    }
  }

  return (
    <div>
      <div className="ssx-subscription-banner__info">
        <HeaderMessage
          level={level}
          messageText={messageText}
          buttonText={'Subscribe'}
          onButtonClick={onClick}
          show={true}
          closeable={closeable}
          rowOnly={isShortTrialMessageOn}
          onClose={() => {
            setBannerDisplayed(false)
          }}
        />
      </div>
    </div>
  )
}

export default SubscriptionBanner
