import { Alert, Button, Col, message, Row } from 'antd'
import ConfirmDeleteModal from 'components/ConfirmDeleteModal'
import { Icon } from 'components/Icon'
import LoadingModule from 'components/LoadingModule'
import PodcastCardModule from 'components/PodcastCardModule'
import PopoverMenu from 'components/PopoverMenu'
import { Paragraph, TypographyPresets } from 'components/Typography'
import take from 'lodash/take'
import {
  BaseItem,
  PodcastItem
} from 'models/talent/talent-profile-module.model'
import * as React from 'react'
import { useCallback, useMemo, useState, useEffect } from 'react'
import copyToClipboard from 'copy-to-clipboard'

import './PodcastLatestSyncItem.scss'
import notification from 'utils/notification'
import { PODCAST_WARNING_TYPE } from 'constants/social'
import { useTypedSelector } from 'redux/rootReducer'
import { selectUserData } from 'redux/User/selector'
import { convertToUrl } from 'utils/url'
import classNames from 'classnames'
import { SocialProfileLinkTypes } from 'redux/User/types'
import { BaseModuleProps } from 'redux/Common/types'
import config from 'config'

interface PodcastLatestSyncItemProps extends BaseModuleProps {
  item: PodcastItem
  loading?: boolean
  onDelete?: (item: PodcastItem) => void
  onEdit?: () => void
  collection?: any
  active?: boolean
  moduleId?: string
}

const PodcastLatestSyncItem = ({
  item,
  onDelete,
  loading,
  collection,
  active = false,
  onEdit,
  moduleId,
  module
}: PodcastLatestSyncItemProps) => {
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [visibleMenu, setVisibleMenu] = useState(false)
  const [showMore, setShowMore] = useState(active)
  const user = useTypedSelector(selectUserData)
  const items = useMemo(() => {
    if (!collection) {
      return []
    }
    return showMore ? collection.items : take(collection.items, 2)
  }, [showMore, collection])

  const onClickDelete = useCallback(() => {
    setShowDeleteConfirm(true)
  }, [])

  const onConfirmDelete = useCallback(() => {
    setShowDeleteConfirm(false)
    onDelete?.(item)
  }, [onDelete, item])
  const onClickAction = useCallback(event => {
    //setShowMore((value) => !value);
    setShowMore(true)
    event.isPropagationStopped()
  }, [])
  useEffect(() => {
    setShowMore(active as boolean)
  }, [active])
  const actionMenu = useMemo(() => {
    return [
      {
        key: 'edit-sync-podcast',
        label: 'Edit',
        itemClassName: 'w-186 p__x--20 p__y--16 height--56',
        labelPreset: 'semibold16' as TypographyPresets,
        onClick: onEdit
      },
      {
        key: 'delete-sync-podcast',
        label: 'Delete',
        className: 'text--red',
        itemClassName: 'w-186 p__x--20 p__y--16 height--56',
        labelPreset: 'semibold16' as TypographyPresets,
        onClick: onClickDelete
      }
    ]
  }, [onEdit, onClickDelete])
  const onCopyLink = (podcast: any) => () => {
    const komiLink =
      config.service.env === 'development'
        ? `${user?.username}.develop.komi.ci`
        : config.service.env === 'staging'
          ? `${user?.username}.staging.komi.ci`
          : `${user?.username}.komi.io`

    copyToClipboard(
      `${komiLink}/podcast/${convertToUrl(podcast.trackName)}?id=${moduleId}`
    )
    notification.success({
      message:
        'The smart link has been copied to clipboard. Your updates need to be published before the link can be accessed.'
    })
  }

  const renderContent = () => {
    if (loading) {
      return <LoadingModule />
    }
    if (
      collection?.warning ===
        PODCAST_WARNING_TYPE.APPLE_AND_SPOTIFY_DO_NOT_HAVE_ANY_SHOW ||
      collection?.status === 'cannot-connect'
    ) {
      return null
    }
    if (!collection?.items?.length) {
      return (
        <div className="podcast-sync-latest-item__content">
          <Row gutter={[10, 10]} justify="center" className="p__t--24 ">
            <div className="max-w-393">
              <Col span={24} className="text__align--center">
                <Icon name="empty-module" />
              </Col>
              <Col span={24} className="text__align--center">
                <Paragraph preset="semibold18" className="d--block m__b--4">
                  No Podcasts Found
                </Paragraph>
                <Paragraph className="opacity--60 leading-22 ">
                  Your linked podcast show could not be found. Try updating your
                  show links to display podcasts again.
                </Paragraph>
              </Col>
            </div>
          </Row>
        </div>
      )
    }
    return (
      <div className="podcast-sync-latest-item__content">
        <Row
          gutter={16}
          wrap={false}
          className="m__b--10"
          align="middle"
          justify="space-between"
        >
          <Col flex={'1'}>
            <Paragraph ellipsis={true} preset="semibold16">
              {collection?.items?.[0]?.collectionName || ''}
            </Paragraph>
          </Col>
          <Col>
            <Paragraph
              ellipsis={true}
              className="opacity--06"
              preset="medium14"
            >
              {collection?.items?.length} &nbsp;
              {collection?.items?.length > 1 ? 'podcasts' : 'podcast'}
            </Paragraph>
          </Col>
        </Row>
        {items.map((podcast: any, index: number) => (
          <div className="p__y--10" key={`${module.id}-${index}`}>
            <PodcastCardModule
              module={module}
              key={index}
              item={podcast}
              rightContent={
                item.id ? (
                  <Button
                    onClick={onCopyLink(podcast)}
                    className="p--0"
                    type="text"
                  >
                    <div className="height--24">
                      <Icon name="copy-link" />
                    </div>
                  </Button>
                ) : (
                  <div />
                )
              }
            />
          </div>
        ))}
        {!showMore &&
          collection.items?.length &&
          collection.items?.length > 2 && (
            <Row className="m__t--10" justify="end">
              <Col>
                <Button onClick={onClickAction} type="text" className="p--0">
                  <Paragraph preset="medium14" className="opacity--06">
                    {!showMore && `+${collection.items?.length - 2} More`}
                  </Paragraph>
                </Button>
              </Col>
            </Row>
          )}
      </div>
    )
  }
  const renderWarningContent = () => {
    if (
      collection?.status === 'cannot-connect' &&
      !item.links.every(link => !!link.url)
    ) {
      const isApple = items.links.some(
        (el: any) =>
          el.type === SocialProfileLinkTypes.APPLE_PODCAST && !!el.url
      )
      return (
        <Paragraph preset="regular16" className="leading-24">
          {`Connection with ${
            isApple ? 'Apple Podcast' : 'Spotify'
          } could not be established at this time.
          Please make sure that your show link is correct. If so, try reloading
          the page or check back later.`}
          <div className="m__t--12">
            {`If there is an issue with ${
              isApple ? 'Apple Podcast' : 'Spotify'
            },
            this module will be hidden from your profile until the connection is
            reestablished. The rest of your profile will not be affected and you
            can continue making and publishing changes as normal.`}
          </div>
        </Paragraph>
      )
    }
    if (
      collection.warning ===
        PODCAST_WARNING_TYPE.APPLE_AND_SPOTIFY_DO_NOT_HAVE_ANY_SHOW ||
      collection?.status === 'cannot-connect'
    ) {
      return (
        <Paragraph preset="regular16" className="leading-24">
          Connection with Spotify and Apple Podcast could not be established at
          this time. Please make sure that your show links are correct. If so,
          try reloading the page or check back later.
          <div className="m__t--12">
            If there is an issue with Spotify and Apple Podcast, this module
            will be hidden from your profile until the connection is
            reestablished. The rest of your profile will not be affected and you
            can continue making and publishing changes as normal.
          </div>
        </Paragraph>
      )
    }

    if (
      [
        PODCAST_WARNING_TYPE.APPLE_PODCAST_SHOW_DO_NOT_EXISTS,
        PODCAST_WARNING_TYPE.SPOTIFY_SHOW_DO_NOT_EXISTS
      ].includes(collection.warning)
    ) {
      if (!!collection.items?.length) {
        return `Connection with ${
          collection.warning ===
          PODCAST_WARNING_TYPE.APPLE_PODCAST_SHOW_DO_NOT_EXISTS
            ? 'Apple Podcast'
            : 'Spotify'
        } could not be established at this time. Please make sure that your show link is correct. If so, try reloading the page or check back later.`
      }
      return 'Your linked podcast show could not be found. Try updating your show links to display podcasts again.'
    }
    return null
  }
  return (
    <div className="podcast-sync-latest-item" onClick={onClickAction}>
      <ConfirmDeleteModal
        show={showDeleteConfirm}
        toggleModal={() => setShowDeleteConfirm(false)}
        cancelLabel="No Thanks!"
        confirmLabel="Delete"
        title="Are you sure you want to delete your synced podcasts?"
        description="The podcast episodes will be deleted from your Komi profile and you can’t undo this action."
        handleConfirm={onConfirmDelete}
        width={520}
      />
      <Alert
        message={undefined}
        className={'m__b--20 p__x--8 p__y--8 bg--darkGray'}
        description={
          'The podcast episodes inside this module are synced automatically. To manually add episodes, create a new podcast module.'
        }
        icon={<Icon name="sm-info" />}
        showIcon
        closeText={<Icon width={24} height={24} name="close-outline" />}
      />

      <Row className="m__b--20" justify="space-between" align="middle">
        <Col>
          <Paragraph preset="semibold18">Synced Podcast Episodes</Paragraph>
        </Col>
        <Col>
          <PopoverMenu
            visible={visibleMenu}
            onChangeVisible={setVisibleMenu}
            data={actionMenu}
          >
            <Icon name="more" />
          </PopoverMenu>
        </Col>
      </Row>
      {collection?.warning &&
        collection?.warning !== PODCAST_WARNING_TYPE.SUCCESS && (
          <Alert
            message={undefined}
            className={classNames(
              'p__y--8 p__x--12 bg--serenade border--none',
              {
                'm__b--20':
                  collection?.warning !==
                    PODCAST_WARNING_TYPE.APPLE_AND_SPOTIFY_DO_NOT_HAVE_ANY_SHOW ||
                  collection?.status === 'cannot-connect'
              }
            )}
            description={renderWarningContent()}
            icon={<Icon name="warning" />}
            showIcon
            closable={false}
          />
        )}
      {renderContent()}
    </div>
  )
}

export default PodcastLatestSyncItem
