import React, { FC } from 'react'
import { OrderItem } from './model/models'
import { useI18n } from '@wordpress/react-i18n'
import { Button, Modal, Notice } from '@wordpress/components'
import { sprintf } from '@wordpress/i18n'
import CustomsInformationHsCodes from './components/CustomsInformationHsCodes'

export declare interface CustomsInformationProps {
  items: Array<OrderItem>
  onChange: () => void
}

const CustomsInformation: FC<CustomsInformationProps> = ({
  items,
  onChange,
}) => {
  const { __, _n, _nx } = useI18n()
  const [modalOpen, setModalOpen] = React.useState<boolean>(false)

  const itemsMissingHsCode = items.filter(
    item => !item.hs_code || item.hs_code === ''
  )

  return (
    <div>
      <Notice isDismissible={false} className="mtl">
        <div className="flex flex-dir-row justify-csb align-ic">
          <div>
            {sprintf(
              _nx(
                '%d item requires an HS code',
                '%d items require an HS code',
                itemsMissingHsCode.length,
                'Validation message presented when one or more items requires an HS code and shipment is labelled as an NVIT (Norske varer i transitt) shipment',
                'posten-bring-checkout'
              ),
              itemsMissingHsCode.length
            )}
          </div>
          <Button
            variant="secondary"
            size="small"
            onClick={() => setModalOpen(true)}
          >
            {_n(
              'Add HS code',
              'Add HS codes',
              itemsMissingHsCode.length,
              'posten-bring-checkout'
            )}
          </Button>
        </div>
      </Notice>
      {modalOpen && (
        <Modal
          className="customs-container"
          title={__('NVIT - Items missing HS code', 'posten-bring-checkout')}
          onRequestClose={() => setModalOpen(!modalOpen)}
          size="large"
          focusOnMount={'firstInputElement'}
          style={{ backgroundColor: 'rgb(247, 247, 247)' }}
        >
          <CustomsInformationHsCodes
            itemsMissingHsCode={itemsMissingHsCode}
            onCancel={() => setModalOpen(!modalOpen)}
            onSave={() => {
              onChange()
              setModalOpen(!modalOpen)
            }}
          />
        </Modal>
      )}
    </div>
  )
}

export default CustomsInformation
