import React, { useState, useContext } from 'react'
import { Modal, ModalBody } from 'reactstrap-wc'
import { t } from '$themelocalization'
import { Icon, ButtonAria } from '$core-components'
import { RootDocumentContext } from '$themeservices'
import './DescriptionEditDialog.scss'

const DescriptionEditDialog = ({
  initialValue = '',
  onSave,
  onClose,
  maxLength = 500,
}) => {
  const [value, setValue] = useState(initialValue)
  const { rootElement } = useContext(RootDocumentContext)()

  const handleSave = () => {
    onSave(value.trim())
  }

  const handleChange = (e) => {
    const newValue = e.target.value
    if (newValue.length <= maxLength) {
      setValue(newValue)
    }
  }


  return (
    <Modal
      isOpen={true}
      className="draft-description-modal"
      backdropClassName="draft-description-modal-backdrop"
      container={rootElement}
    >
      <div className="draft-description-modal-header">
        <div className="draft-description-modal-title">{t('Drafts.Dialog.Description.Title')}</div>
        <ButtonAria className="button button-transparent close-btn" onClick={onClose}>
          <Icon name="close_black.svg" width="14px" height="14px" />
        </ButtonAria>
      </div>
      <ModalBody className="draft-description-modal-body">
        <div className="draft-description-form">
          <label className="draft-description-label">
            {t('Drafts.Dialog.Description.Label')}
          </label>
          <textarea
            className="draft-description-textarea"
            value={value}
            onChange={handleChange}
            placeholder={t('Drafts.Dialog.Description.Placeholder')}
            rows={3}
            maxLength={maxLength}
          />
          <p className="draft-description-note">
            {t('Drafts.Dialog.Description.Note')}
          </p>
        </div>

        <div className="draft-description-modal-actions">
          <ButtonAria
            className="button button-secondary"
            text={t('Drafts.Dialog.Description.Cancel')}
            onClick={onClose}
          />
          <ButtonAria
            className="button button-primary"
            text={t('Drafts.Dialog.Description.Save')}
            onClick={handleSave}
          />
        </div>
      </ModalBody>
    </Modal>
  )
}

export default DescriptionEditDialog
