import { SocialLinkType, getSocialLinkConfig } from '@komi-app/creator-ui'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { Alert } from 'antd'
import classNames from 'classnames'
import { defaultSocialTags } from 'constants/social'
import * as React from 'react'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import {
  selectTalentProfile,
  selectTalentRevert,
  selectUserData
} from 'redux/User/selector'
import { SocialProfileLinkItem, User } from 'redux/User/types'
import { useTypedSelector } from 'redux/rootReducer'
import { Icon } from '../../../components/Icon'
import ProfileSocialLinkList from '../../../components/ProfileSocialLinkList'
import { Paragraph } from '../../../components/Typography'
import {
  setTalentProfileAction,
  updateTalentRevertAction
} from '../../../redux/User/actions'
import './ProfileSocialLinks.scss'

interface ProfileSocialLinksProps {
  className?: string
}
const ProfileSocialLinks = ({ className }: ProfileSocialLinksProps) => {
  const dispatch = useDispatch()
  const user: User | null | undefined = useTypedSelector(selectUserData)

  const [isInit, setIsInit] = useState(false)
  const [tags] = React.useState(defaultSocialTags)
  const [links, setLinks] = useState<SocialProfileLinkItem[]>([])
  const [showAlert, setShowAlert] = useState(false)
  const talentProfile = useTypedSelector(selectTalentProfile)
  const talentRevert = useTypedSelector(selectTalentRevert)
  const isTemplateSelectionOn = useFeatureIsOn(
    FLAGS.GS_146_ADD_TEMPLATE_SELECTION
  )
  const hasNewSocialLinks = useFeatureIsOn(
    FLAGS.FEAT_SB_186_ADDITIONAL_SOCIAL_LINKS
  )

  useEffect(() => {
    if (!user?.talentProfile?.id) {
      return
    }
    const show = localStorage.getItem(
      `ALERT_SOCIAL_LINKS_${user?.talentProfile?.id}`
    )
    if (!show) {
      setShowAlert(true)
      localStorage.setItem(
        `ALERT_SOCIAL_LINKS_${user?.talentProfile?.id}`,
        'true'
      )
    }
  }, [user?.talentProfile?.id])
  useEffect(() => {
    if (talentRevert) {
      dispatch(updateTalentRevertAction(false))
      setIsInit(false)
    }
  }, [talentProfile?.socialProfileLinks, talentRevert])

  const handleSetLinks = (profileLinks: SocialProfileLinkItem[]) => {
    setLinks(profileLinks)
    const socialProfileLinks = profileLinks
      .filter(item => item.value)
      .map(el => ({ type: el.key, link: el.value }))
    dispatch(
      setTalentProfileAction({
        socialProfileLinks
      })
    )
  }

  useEffect(() => {
    if (user && !isInit) {
      setIsInit(true)
      const profileLinks: SocialProfileLinkItem[] =
        user?.talentProfile?.socialProfileLinks?.map(item => {
          const tag = tags.find(i => i.key === item.type)
          return {
            ...tag,
            edit: false,
            value: item.link
          } as SocialProfileLinkItem
        }) || []
      setLinks(profileLinks || [])
    }
  }, [user?.talentProfile?.socialProfileLinks, isInit])

  useEffect(() => {
    if (user && isTemplateSelectionOn) {
      const profileLinks: SocialProfileLinkItem[] = (
        user?.talentProfile?.socialProfileLinks?.map(item => {
          if (hasNewSocialLinks) {
            // this typecasting is awful but we're stuck with it until we can remove the legacy social link types
            const linkType = item.type as unknown as SocialLinkType
            const link = getSocialLinkConfig(linkType)

            // map the new type to fit the old type,
            return {
              key: linkType,
              name: link.label,
              icon: 'website',
              edit: false,
              value: item.link
            } as SocialProfileLinkItem
          }

          const tag = tags.find(i => i.key === item.type)
          return {
            ...tag,
            edit: false,
            value: item.link
          } as SocialProfileLinkItem
        }) || []
      ).filter(item => item.name)
      setLinks(profileLinks || [])
    }
  }, [
    user?.talentProfile?.socialProfileLinks,
    isTemplateSelectionOn,
    hasNewSocialLinks
  ])

  return (
    <div className={classNames('profile-social-links', className)}>
      <Paragraph
        className="m__b--20 text--grey4 leading-22"
        preset="regular14"
        data-testid="profile-social-links__subtitle"
      >
        You can add up to 7 social profile links to your page.
      </Paragraph>
      {showAlert && (
        <Alert
          message={undefined}
          className={classNames(
            'm__b--26 p__x--8 p__y--8 bg--darkGray shopify-module__alert'
          )}
          description={
            'Tip: if you want to link specific content, e.g. videos or tracks, you can do so in the module section.'
          }
          icon={<Icon name="info" />}
          showIcon
          closeText={<Icon width={24} height={24} name="close-outline" />}
          onClose={() => setShowAlert(false)}
        />
      )}
      <ProfileSocialLinkList
        className="module-profile-social"
        links={links}
        onSetLinks={handleSetLinks}
      />
    </div>
  )
}

export default ProfileSocialLinks
