import React, { useState, useRef } from 'react'
import { observer } from 'mobx-react-lite'
import { t } from '$themelocalization'
import { formatDate } from '../../cart/model/utils'
import { Icon } from '$core-components'
import DraftItemThumbnail from './DraftItemThumbnail'
import DraftItemActions from './DraftItemActions'
import DraftDescription from './DraftDescription'
import DraftIncludedProducts from './DraftIncludedProducts'
import DraftConfirmationDialog from '../DraftConfirmationDialog'
import DescriptionEditDialog from '../DescriptionEditDialog'
import InfoMessage from '../../cart/CartItem/InfoMessage'
import './index.scss'

const DraftItem = ({ item, showDescription, showSaveAction, model }) => {
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false)
  const [showSaveDialog, setShowSaveDialog] = useState(false)
  const [alertMessage, setAlertMessage] = useState('')
  const [tooltipOpen, setTooltipOpen] = useState(true)
  const actionTypeRef = useRef(null)
  const actionHandledRef = useRef(false)
  const animationDoneRef = useRef(false)
  const saveDoneRef = useRef(false)
  const savePromiseRef = useRef(null)
  const containerRef = useRef(null)

  const finalizeMove = () => {
    if (actionHandledRef.current) return
    if (actionTypeRef.current !== 'move') return
    if (!animationDoneRef.current || !saveDoneRef.current) return

    actionHandledRef.current = true
    savePromiseRef.current = null
    model.moveDraftToSaved(item, item.description)
  }

  const handleDeleteConfirm = async () => {
    setShowDeleteConfirmation(false)
    actionTypeRef.current = 'delete'
    actionHandledRef.current = false
    animationDoneRef.current = false
    saveDoneRef.current = false
    savePromiseRef.current = null
    setAlertMessage(t('Drafts.Item.Deleted'))
    item.delete({ deferRemove: true }).catch((error) => {
      console.error(error)
      setAlertMessage('')
      actionTypeRef.current = null
      actionHandledRef.current = false
      animationDoneRef.current = false
      saveDoneRef.current = false
      savePromiseRef.current = null
    })
  }

  const handleTransitionEnd = (e) => {
    if (e.target !== containerRef.current) return
    if (e.propertyName !== 'max-height') return
    if (!alertMessage) return

    if (actionTypeRef.current === 'delete') {
      if (actionHandledRef.current) return
      actionHandledRef.current = true
      model.removeItemFromLists(item)
    } else if (actionTypeRef.current === 'move') {
      animationDoneRef.current = true
      finalizeMove()
    }
  }

  const handleSave = () => {
    if (alertMessage) return
    actionTypeRef.current = 'move'
    actionHandledRef.current = false
    animationDoneRef.current = false
    saveDoneRef.current = false
    setAlertMessage(t('Drafts.Item.MovedToManual'))
    const promise = item.save(item.description || '', { deferMove: true })
    savePromiseRef.current = promise
    promise
      .then(() => {
        saveDoneRef.current = true
        finalizeMove()
      })
      .catch((error) => {
        console.error(error)
        setAlertMessage('')
        actionTypeRef.current = null
        animationDoneRef.current = false
        saveDoneRef.current = false
        savePromiseRef.current = null
        actionHandledRef.current = false
      })
  }

  const handleDescriptionEdit = () => {
    setShowSaveDialog(true)
  }

  const handleSaveConfirm = async (description) => {
    setShowSaveDialog(false)
    await item.save(description)
  }

  const handleContinue = () => {
    item.continue()
  }

  const errorMessages = item.validations
    ?.map(v => ({ message: v.Message }))

  return (
    <div
      className={`draft-list-item ${alertMessage ? 'close-item' : ''} ${tooltipOpen ? 'tooltip-open' : ''}`}
      ref={containerRef}
      onTransitionEnd={handleTransitionEnd}
    >
      <div className={`draft-item-wrapper ${alertMessage ? 'alert-open' : ''}`}>
        <div className="draft-item-content">
          <div className="draft-item-thumbnail-container">
            <DraftItemThumbnail
              src={item.thumbnailUrl}
              onClick={handleContinue}
              disabled={!item.isProductAvailable}
            />
          </div>

          <div className="draft-item-info">
            <div className="draft-item-product-name">{item.product?.name}</div>

            {showDescription && (
              <DraftDescription
                description={item.description}
                onEdit={handleDescriptionEdit}
              />
            )}

            {item.hasSubItems && (
              <DraftIncludedProducts 
                subItems={item.subItems} 
                onTooltipChange={setTooltipOpen}
              />
            )}
            <div className="draft-item-date">{formatDate(item.creationDate)}</div>

            {!item.isProductAvailable && (
              <div className="draft-item-unavailable">
                <span className="unavailable-icon"><Icon name={`cart_error.svg`} width="12px" height="12px" wrapperClassName={``} /></span>
                <span className="unavailable-text">{t('Drafts.Item.ProductNotAvailable')}</span>
              </div>
            )}
          </div>

          <DraftItemActions
            item={item}
            showSaveAction={showSaveAction}
            onContinue={handleContinue}
            onSave={handleSave}
            onDelete={() => setShowDeleteConfirmation(true)}
          />
        {(errorMessages?.length > 0) && (
          <div className="draft-item-validation-messages cart-item-warning-error-messages">
            {errorMessages?.length > 0 && <InfoMessage type="error" messages={errorMessages} />}
          </div>
        )}
        </div>

        <div className="draft-item-alert">
          <div className="content">
            <div className="alert-icon">
              <Icon name="close_black.svg" width="14px" height="14px" />
            </div>
            <div className="alert-message">{alertMessage}</div>
          </div>
        </div>
      </div>

      <DraftConfirmationDialog
        open={showDeleteConfirmation}
        itemThumbnail={item.thumbnailUrl}
        title={t('Drafts.Dialog.Delete.Title')}
        confirmationText={t('Drafts.Dialog.Delete.Confirmation')}
        confirmButtonText={t('Drafts.Button.Delete')}
        rejectButtonText={t('Drafts.Button.Cancel')}
        onConfirm={handleDeleteConfirm}
        onReject={() => setShowDeleteConfirmation(false)}
      />

      {showSaveDialog && (
        <DescriptionEditDialog
          initialValue={item.description}
          onSave={handleSaveConfirm}
          onClose={() => setShowSaveDialog(false)}
          maxLength={500}
        />
      )}
    </div>
  )
}

export default observer(DraftItem)
