import _identity from 'lodash/identity'
import _isEmpty from 'lodash/isEmpty'
import _some from 'lodash/some'
import React from 'react'

import { submitShareAction } from '../../api/preRegistrationComplete'
import { CopyField } from '../common/CopyField'
import SocialButtons from '../confirmationContainer/social-buttons'
import { getShuffleMethodByName, shareOptionsAdapter } from './utils'

export const ShareOptions = (props: IShareOptionsProps) => {
  const {
    classNamePrefix,
    data,
    hasCopyIcon = true,
    onLinkCopied = _identity,
    headerText = 'Share with your friends here ...',
    hash,
    updateShareActionData,
    shareActionData,
  } = props

  const {
    attributes: { actions, shareUrl },
  } = data

  const shareButtons = shareOptionsAdapter(actions, shareUrl)
  const isShareLinkEnabled = _some(
    actions,
    (item: IShareOptionsActionData) => item.action === 'shared_url'
  )
  const onAfterShare = async (eventActionId: string | undefined) => {
    const { shareActionToken, tokenShuffleMethod } = shareActionData
    const accessToken = getShuffleMethodByName(tokenShuffleMethod)(shareActionToken)
    if (typeof eventActionId === 'string') {
      await submitShareAction({
        eventActionId,
        accessToken,
        hash,
      })
      updateShareActionData()
    }
  }

  return (
    <div className={`${classNamePrefix}_share_options`}>
      {!_isEmpty(actions) && (
        <>
          <div className={`${classNamePrefix}_share_header`}>{headerText}</div>
          <SocialButtons
            shareLink={data.attributes.shareUrl}
            name=""
            appId=""
            showDefaultShareButtons={false}
            shareButtons={shareButtons}
            titleText=""
            footerText=""
            onAfterShare={(eventActionId: string | undefined) =>
              onAfterShare(eventActionId)
            }
          />
          {isShareLinkEnabled && (
            <div className={`${classNamePrefix}_share_btn_inner`}>
              <CopyField
                copyValue={shareUrl}
                onLinkCopied={onLinkCopied}
                hasCopyIcon={hasCopyIcon}
                classNamePrefix={classNamePrefix}
                messageText="Share your link"
              />
            </div>
          )}
        </>
      )}
    </div>
  )
}
