import { SocialIcon, SocialLinkType } from '@komi-app/creator-ui'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import When from '@komi-app/when'
import { Button, Col, Popover, Row } from 'antd'
import DragDropButton from 'components/Button/DragDropButton'
import ConfirmDeleteModal from 'components/ConfirmDeleteModal'
import LabelTooltip from 'components/LabelTooltip/LabelTooltip'
import { useTikTokMetadata } from 'hooks/useTikTokMetadata'
import { TikTokItem } from 'models/talent/talent-profile-module.model'
import ItemVisibilityToggle from 'pages/Profile/ModuleEditor/ItemVisibilityToggle'
import React, { useMemo, useState } from 'react'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import { BaseModuleProps } from 'redux/Common/types'
import { convertHTMLEntity } from 'utils/string'
import CardModuleAction from '../CardModuleAction'
import { Icon } from '../Icon'
import './TikTokVideoCardModule.scss'

interface Props extends BaseModuleProps {
  item: TikTokItem
  loading?: boolean
  titleShortcut?: boolean
  onEdit?: (item: TikTokItem) => void
  onDelete?: (item: TikTokItem) => void
  dragHandleProps?: DraggableProvidedDragHandleProps
  disableDrag?: boolean
  hideActions?: boolean
  hideVisibility?: boolean
  onVisibilityChange?: (item: TikTokItem) => void
}

const MAX_TITLE_LENGTH = 200

const TikTokVideoCardModule: React.FC<Props> = ({
  item,
  disableDrag = false,
  dragHandleProps,
  onEdit,
  onDelete,
  hideActions = false,
  hideVisibility = false,
  module,
  onVisibilityChange
}) => {
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [visibleAction, setVisibleAction] = useState(false)
  const isAutomationEnabled = useFeatureIsOn(FLAGS.SHORT_VIDEO_AUTOMATION)
  const { data: metadata } = useTikTokMetadata(item.url)

  const onDeleteConfirm = () => {
    typeof onDelete === 'function' && onDelete(item)
    setShowDeleteConfirm(false)
  }

  const title = useMemo(() => {
    let title = ''

    if (metadata?.type === 'unavailable') {
      title = 'Video unavailable'
    }

    if (metadata?.type === 'video' && metadata.title) {
      title = metadata.title
    }

    if (title.length > MAX_TITLE_LENGTH) {
      title = title.slice(0, MAX_TITLE_LENGTH) + '...'
    }

    return convertHTMLEntity(title)
  }, [metadata])

  const subtitle = useMemo(() => {
    if (!isAutomationEnabled) {
      return item.url
    }

    if (metadata?.type === 'unavailable') {
      return ''
    }

    return metadata?.author_name || ''
  }, [isAutomationEnabled, item, metadata])

  const icon = useMemo(() => {
    if (metadata?.type === 'unavailable') {
      return <Icon name="module-warning" />
    }

    if (metadata?.type === 'video' && metadata.thumbnail_url) {
      return <img src={metadata.thumbnail_url} />
    }

    return <SocialIcon social={SocialLinkType.TIKTOK} mode="color" />
  }, [metadata])

  return (
    <React.Fragment>
      {!hideActions && (
        <ConfirmDeleteModal
          show={showDeleteConfirm}
          toggleModal={() => setShowDeleteConfirm(false)}
          cancelLabel="No Thanks!"
          confirmLabel="Delete"
          title="Are you sure you want to delete this TikTok video?"
          description="This TikTok video will be deleted and you can’t undo this action."
          handleConfirm={onDeleteConfirm}
          width={520}
        />
      )}
      <div className="border-box d--flex tiktok-video-card border__radius--8">
        <Row wrap={false} className="full-width">
          <Col className="tiktok-video-card__picture">{icon}</Col>
          <Col flex={'1'}>
            <Row
              className="tiktok-video-card__content p__x--16 p__y--16 full-width full-height"
              wrap={false}
              align="middle"
            >
              <Col flex="1">
                <LabelTooltip
                  preset="semibold16"
                  className="d--block"
                  ellipsis={{ rows: 1 }}
                  label={title as string}
                  maxLength={(title as string).length}
                  showTooltip={(title as string).length > 36}
                />
                <When
                  value={subtitle.length > 0}
                  then={
                    <LabelTooltip
                      preset="regular14"
                      className="d--block text--grey4 m__t--4 "
                      label={subtitle as string}
                      ellipsis={{ rows: 1 }}
                      maxLength={(subtitle as string).length}
                      showTooltip={(subtitle as string).length > 36}
                    />
                  }
                />
              </Col>
              {!hideVisibility && (
                <Col>
                  <ItemVisibilityToggle
                    module={module}
                    item={item}
                    onClick={
                      onVisibilityChange && (() => onVisibilityChange(item))
                    }
                  />
                </Col>
              )}
              {!hideActions && (
                <Col className={'p__l--24'}>
                  <Row wrap={false} gutter={16} align="middle">
                    <Col>
                      <Popover
                        visible={visibleAction}
                        placement="bottomRight"
                        overlayClassName="module-editor-overlay"
                        arrowContent={null}
                        content={
                          <CardModuleAction
                            onEdit={onEdit && (() => onEdit?.(item))}
                            onDelete={
                              onDelete && (() => setShowDeleteConfirm(true))
                            }
                            toggleVisible={setVisibleAction}
                          />
                        }
                        trigger={['click']}
                        onVisibleChange={setVisibleAction}
                      >
                        <Button
                          className="p--0 d--flex align__items--center height--24 min-h-auto"
                          type="link"
                          onClick={() => setVisibleAction(true)}
                        >
                          <Icon name="more" />
                        </Button>
                      </Popover>
                    </Col>
                    {dragHandleProps ? (
                      <Col>
                        <DragDropButton
                          className="p__x--0 p__y--0"
                          dragType="vertical"
                          dragHandleProps={dragHandleProps}
                          disabled={disableDrag}
                        />
                      </Col>
                    ) : null}
                  </Row>
                </Col>
              )}
            </Row>
          </Col>
        </Row>
      </div>
    </React.Fragment>
  )
}

export default TikTokVideoCardModule
