import React, { useState } from 'react'
import { observer } from 'mobx-react-lite'
import sanitizeHTML from 'sanitize-html'
import { t } from '$themelocalization'
import { Icon, ButtonAria } from '$core-components'
import DraftItem from '../DraftItem'
import DraftConfirmationDialog from '../DraftConfirmationDialog'
import DraftsModel from '../model/DraftsModel'
import { useMobile } from '$themehooks'
import './index.scss'

const DraftSection = ({
  model,
  section,
  items,
  filteredCount,
  isExpanded,
  onToggle,
  maxDrafts,
}) => {
  const [showDeleteAllConfirmation, setShowDeleteAllConfirmation] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const isSavedSection = section === DraftsModel.DRAFT_SECTIONS.SAVED
  const isMobile = useMobile()
  const title = isSavedSection
    ? t('Drafts.Section.Saved')
    : t('Drafts.Section.Latest', { count: maxDrafts || 3 })

  const shortTitle = isSavedSection
    ? t('Drafts.Section.SavedShort')
    : t('Drafts.Section.LatestShort')

  const titleToShow = isMobile ? shortTitle : title

  const handleDeleteAll = async () => {
    setShowDeleteAllConfirmation(false)
    setIsDeleting(true)
    try {
      await model.deleteAllInSection(section)
    } finally {
      setIsDeleting(false)
    }
  }

  const handleDeleteAllClick = (e) => {
    e.stopPropagation()
    if (filteredCount === 0 || isDeleting) return
    setShowDeleteAllConfirmation(true)
  }

  const deleteAllConfirmation = (
    <span dangerouslySetInnerHTML={{
      __html: sanitizeHTML(t('Drafts.Dialog.DeleteAll.Confirmation'), {
        allowedTags: ['b'],
        allowedAttributes: {},
      }),
    }} />
  )

  const noResultsMessage = model.searchQuery
    ? t('Drafts.NoResultsFor', { search: model.searchQuery })
    : t('Drafts.NoItemsToDisplay')

  return (
    <div className={`draft-list-section ${isExpanded ? 'is-open' : 'is-closed'}`}>
      <div
        className="draft-list-section-header"
        role="group"
        onClick={onToggle}
      >
        <div
          className="draft-list-section-title-container"
          role="button"
          tabIndex={0}
          aria-expanded={isExpanded}
          aria-label={titleToShow}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault()
              e.stopPropagation()
              onToggle()
            }
          }}
        >
          <Icon
            name="arrowDown.svg"
            width="16px"
            height="16px"
            className={`draft-list-section-arrow ${isExpanded ? 'arrow-up' : 'arrow-down'}`}
            ariaHidden="true"
          />
          <span className="draft-list-section-title">{titleToShow}</span>
        </div>

        <div className="draft-list-section-actions">
          <ButtonAria
            className="button button-transparent draft-delete-all-text"
            onClick={handleDeleteAllClick}
            disabled={filteredCount === 0 || isDeleting}
          >
            {isMobile ? <><Icon wrapperClassName="draft-delete-all-icon" name="cart_delete.svg" width="16px" height="16px" title={t('Drafts.Button.DeleteAll')} /><span>{`(${filteredCount})`}</span></> : <span>{`${t('Drafts.Button.DeleteAll')} (${filteredCount})`}</span>}
          </ButtonAria>
        </div>
      </div>

      <div
        className={`draft-list-section-body ${isExpanded ? 'is-expanded' : 'is-collapsed'}`}
        aria-hidden={!isExpanded}
        inert={!isExpanded ? '' : undefined}
      >
        <div className="draft-list-section-body-inner">
          {items.length === 0 ? (
            <div className="draft-list-empty" role="status" aria-live="polite">{noResultsMessage}</div>
          ) : (
            items.map((item) => (
              <DraftItem
                key={item.orderItemId}
                item={item}
                showDescription={isSavedSection}
                showSaveAction={!isSavedSection}
                model={model}
              />
            ))
          )}
        </div>
      </div>

      <DraftConfirmationDialog
        open={showDeleteAllConfirmation}
        title={t('Drafts.Dialog.DeleteAll.Title')}
        confirmationText={deleteAllConfirmation}
        confirmButtonText={`${t('Drafts.Button.Delete')} (${filteredCount})`}
        rejectButtonText={t('Drafts.Button.Cancel')}
        onConfirm={handleDeleteAll}
        onReject={() => setShowDeleteAllConfirmation(false)}
      />
    </div>
  )
}

export default observer(DraftSection)
