import React, { useState } from 'react'
import { observer } from 'mobx-react-lite'
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 = (
    <>
      {t('Drafts.Dialog.DeleteAll.Confirmation.Part1')}
      <strong>{t('Drafts.Dialog.DeleteAll.Confirmation.Part2')}</strong>
      {t('Drafts.Dialog.DeleteAll.Confirmation.Part3')}
    </>
  )

  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" onClick={onToggle}>
        <div className="draft-list-section-title-container">
          <Icon
            name="arrowDown.svg"
            width="16px"
            height="16px"
            className={`draft-list-section-arrow ${isExpanded ? 'arrow-up' : 'arrow-down'}`}
          />
          <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'}`}
      >
        <div className="draft-list-section-body-inner">
          {items.length === 0 ? (
            <div className="draft-list-empty">{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)
