import Layout from 'antd/lib/layout'
import { Content } from 'antd/lib/layout/layout'
import classnames from 'classnames'
import Loading from 'components/Loading'
import SubscriptionBanner from 'components/SubscriptionBanner'
import PreviewLayoutBanner from './PreviewLayoutBanner'

import { useWindowSize } from 'hooks/useWindowSize'
import moment from 'moment'
import React, {
  createContext,
  MouseEvent,
  ReactNode,
  Suspense,
  useCallback,
  useEffect,
  useMemo,
  useState
} from 'react'
import { useTypedSelector } from 'redux/rootReducer'
import {
  selectCollaborator,
  selectIsCollaborator,
  selectTalentProfile,
  selectUserCustomer,
  selectUserData
} from 'redux/User/selector'
import { firebaseService } from 'services'
import './PreviewLayout.scss'
import { useHistory } from 'react-router-dom'

import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'

import {
  MenuItem,
  MenuItemCombo,
  MenuItemGroup,
  MenuItemLabel,
  MenuItemLink,
  MenuItemType,
  Navbar
} from '@komi-app/creator-ui'

import { RequestAProfileModal } from 'components/PreviewLayoutHeader/RequestAProfileModal'
import useNavUser from 'hooks/useNavUser'
import useNavMenu from 'hooks/useNavMenu'
import { useAnalytics } from '../../hooks/useAnalytics'
import { NavBarClickProperties, SEGMENT_EVENTS } from '../../constants/segment'

export const SubscriptionBannerContext = createContext<
  typeof SubscriptionBanner
>(null!)

interface IProps {
  children?: ReactNode
  className?: string
}

export function getNavBarTrackingProperties(
  item: MenuItem
): NavBarClickProperties | undefined {
  const { type } = item

  if (
    type === MenuItemType.LINK ||
    type === MenuItemType.GROUP ||
    type === MenuItemType.LABEL
  ) {
    const castItem = item as MenuItemLink | MenuItemGroup | MenuItemLabel
    return {
      Type: type,
      Name: castItem.name
    }
  } else if (type === MenuItemType.COMBO_LINK) {
    const castItem = item as MenuItemCombo
    return {
      Type: 'PROFILE_LINK',
      Name: castItem.name
    }
  } else if (type === MenuItemType.COMBO_ACTION) {
    return {
      Type: 'PROFILE_ACTION'
    }
  } else if (type === MenuItemType.POPUP) {
    return {
      Type: 'USER_MENU'
    }
  } else if (type === MenuItemType.MOBILE_MENU_ICON) {
    return {
      Type: 'MOBILE_MENU_ICON'
    }
  } else if (type === MenuItemType.PROFILE) {
    return {
      Type: 'PROFILE'
    }
  }
}

const PreviewLayout: React.FC<IProps> = ({ children, className = '' }) => {
  const { height } = useWindowSize()
  const history = useHistory()
  const { sendSegmentEvent } = useAnalytics()
  const useCoupon = useFeatureIsOn(FLAGS.FEAT_AIR_649_REDEEM_DISCOUNT)
  const talentProfile = useTypedSelector(selectTalentProfile)
  const isCollaborator = useTypedSelector(selectIsCollaborator)
  const collaborator = useTypedSelector(selectCollaborator)
  const user = useTypedSelector(selectUserData)
  const customerData = useTypedSelector(selectUserCustomer)
  const customer = useCoupon ? customerData : void 0

  const url = history.location.pathname

  const attributeKey = useMemo(
    () => (talentProfile?.id ? `talent/${talentProfile?.id}` : null),
    [talentProfile?.id]
  )

  const navMenu = useNavMenu()
  const navUser = useNavUser()
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const navBarClick = createTracker(CreatorEvent.NAV_BAR_CLICK)

  // Navlink Handler, that sends Segment events before redirecting to link <- also replaces OnClickAdmin Dashboard
  const onClickItem = (e: MouseEvent, item: MenuItem) => {
    const properties = getNavBarTrackingProperties(item)
    useAnalyticsSDK
      ? navBarClick({
          type: properties?.Type,
          name: properties?.Name
        })
      : sendSegmentEvent(SEGMENT_EVENTS.NAV_BAR_CLICK, properties)

    if ('key' in item) {
      const { key } = item

      switch (key) {
        case 'request-profile':
          return setRequestNewProfileModalIsOpen(true)
      }
    }
  }

  //move to new comp with navbar?
  const [requestNewProfileModalIsOpen, setRequestNewProfileModalIsOpen] =
    useState(false)

  // Write last connection times to Firebase
  const updateAttributesData = useCallback(
    async (data = {}) => {
      if (attributeKey) {
        try {
          const currentAttrs =
            (await firebaseService.getOnce(attributeKey)).val() || {}

          let newAttrs = {
            ...currentAttrs,
            ...data,
            [`${collaborator?.id ?? user?.id}`]: {
              lastConnection: moment().toISOString()
            }
          }
          if (currentAttrs?.startedAt) {
            newAttrs = {
              ...currentAttrs,
              talentLastConnection: moment().toISOString()
            }
          }
          await firebaseService.write(attributeKey, newAttrs)
        } catch (error) {
          console.error('error: ', error)
        }
      }
    },
    [attributeKey, collaborator?.id, user?.id, isCollaborator]
  )

  // Perform the above attributes writing every 5 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      updateAttributesData()
    }, 5000)
    return () => clearInterval(interval)
  }, [updateAttributesData])

  const layoutClass = classnames(
    'preview-layout-creator-ui',
    'preview-layout',
    className
  )

  const [bannerDisplayed, setBannerDisplayed] = useState(false)

  const onInvalidPage = () =>
    ['/account-setting', '/data-export', '/analytics'].includes(
      history.location.pathname
    ) // TODO: "/data-export" can be removed after DCA is deployed

  const displayBanner = useCoupon
    ? !!user && !!customer && !onInvalidPage()
    : !onInvalidPage()

  const pageContentClass = classnames({
    'preview-layout__page-content': true,
    'preview-layout__page-content--trial-banner':
      bannerDisplayed && !onInvalidPage(),
    'preview-layout__page-content--banner-dismissed': !bannerDisplayed
  })

  // TODO: update PreviewLayoutBanner prop for isSubscribed with GET request on /subscriptions/dca
  const isSubscribed = false

  // TODO: update PreviewLayoutBanner prop for isExceedingContacts with logic to check if user has exceeded contacts allowance
  const isExceedingContacts = false

  //generate user based on props

  return (
    <>
      <Layout
        className={layoutClass}
        style={{
          minHeight: `${height}px`
        }}
      >
        <div className="navbar-styles">
          <Navbar onClickItem={onClickItem} User={navUser} Menu={navMenu} />
          <RequestAProfileModal
            visible={requestNewProfileModalIsOpen}
            onCancel={() => setRequestNewProfileModalIsOpen(false)}
            onOk={() => setRequestNewProfileModalIsOpen(false)}
          />
        </div>
        <Content>
          <Layout className="preview-layout__content">
            {displayBanner && (
              <PreviewLayoutBanner
                url={url}
                setBannerDisplayed={setBannerDisplayed}
                isSubscribed={isSubscribed}
                isExceedingContacts={isExceedingContacts}
                customer={customer}
              />
            )}
            <div className="fluid-container d--flex flex--1 flex__direction--column">
              <Content className={pageContentClass}>
                <Suspense fallback={<Loading />}>{children}</Suspense>
              </Content>
            </div>
          </Layout>
        </Content>
      </Layout>
    </>
  )
}

export default PreviewLayout
