import React, { FC, useState } from 'react'
import { Order } from '../model/models'
import { Text, Link } from '@wordpress/ui'
import { ServiceIcon } from '@mybring/iconsystem'
import {
  Button,
  DropdownMenu,
  MenuGroup,
  MenuItem,
  Popover,
  Snackbar,
  Spinner,
} from '@wordpress/components'
import { useI18n } from '@wordpress/react-i18n'
import { more, redo, undo, pages, external } from '@wordpress/icons'
import apiFetch from '@wordpress/api-fetch'
import OrderListDetails from './OrderListDetails'

export declare interface BookedOrderListItemProps {
  order: Order
}

const BookedOrderListItem: FC<BookedOrderListItemProps> = ({ order }) => {
  const [menuOpen, setMenuOpen] = useState(false)
  const [displayOrderDetails, setDisplayOrderDetails] = useState(false)
  const [labelFailure, setLabelFailure] = useState(false)
  const [labelInProgress, setLabelInProgress] = useState(false)
  const [waybillInProgress, setWaybillInProgress] = useState(false)
  const [returnLabelInProgress, setReturnLabelInProgress] =
    React.useState(false)
  const { __ } = useI18n()

  const getLabel = async (labelType: string) => {
    setLabelFailure(false)
    const newTab = window.open('', '_blank')
    const path =
      labelType === 'WAYBILL'
        ? `/posten-bring-checkout/waybills?orderIds=${order.order_id}`
        : `/posten-bring-checkout/labels?orderIds=${order.order_id}&labelType=${labelType}`
    const response = await apiFetch<Response, false>({
      path: path,
      method: 'GET',
      headers: {
        Accept: 'application/pdf',
      },
      parse: false,
    })
      .catch(_ => {
        setLabelFailure(true)
      })
      .finally(() => {
        setLabelInProgress(false)
        setReturnLabelInProgress(false)
        setWaybillInProgress(false)
      })

    if (response?.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(
        new Blob([blob], { type: 'application/pdf' })
      )

      if (newTab) {
        newTab.location.href = url
      }
    }
  }

  return (
    <li className="order-list-item" key={order.order_id}>
      <div className="order-list-item__content flex align-ic flex-dir-row">
        <div className="pas flex flex-dir-row gas align-ic justify-csb flex-1">
          <div className="flex flex-dir-row gam align-ic">
            <div className="mrxl order-id">
              <Button
                role="button"
                onClick={() => setDisplayOrderDetails(visible => !visible)}
              >
                <Text variant={'heading-xl'}>#{order.order_id}</Text>
                {displayOrderDetails && (
                  <Popover
                    onClickOutside={() => setDisplayOrderDetails(false)}
                    focusOnMount={false}
                    onClose={() => setDisplayOrderDetails(false)}
                  >
                    <OrderListDetails order={order} />
                  </Popover>
                )}
              </Button>
            </div>
            <div className="flex flex-dir-row gas align-ic">
              <>
                <ServiceIcon name="parcel" height={26} className="flex" />
                <div className="mll">
                  <Link
                    href={order.mybring_bookings[0].trackingUrl}
                    openInNewTab={true}
                    tone={'neutral'}
                  >
                    {order.mybring_bookings[0].consignmentNumber}
                  </Link>
                </div>
              </>
            </div>
            {labelFailure && (
              <Snackbar
                explicitDismiss
                politeness="assertive"
                onRemove={() => setLabelFailure(false)}
              >
                {__(
                  'An error occurred while generating label. Please try again',
                  'posten-bring-checkout'
                )}
              </Snackbar>
            )}
          </div>
          <div>
            <DropdownMenu
              icon={more}
              open={menuOpen}
              onToggle={setMenuOpen}
              label={__('Menu', 'posten-bring-checkout')}
            >
              {({ onToggle }) => (
                <>
                  <MenuGroup label={__('Labels', 'posten-bring-checkout')}>
                    <MenuItem
                      icon={
                        labelInProgress ? (
                          <Spinner
                            style={{
                              height: '16px',
                              width: '16px',
                              margin: '0 4px',
                            }}
                          />
                        ) : (
                          redo
                        )
                      }
                      iconPosition="right"
                      onClick={() => {
                        setLabelInProgress(true)
                        getLabel('LABEL')
                        onToggle()
                      }}
                    >
                      {__('Print label', 'posten-bring-checkout')}
                    </MenuItem>
                    {order.mybring_bookings[0].waybillUrl && (
                      <MenuItem
                        icon={
                          waybillInProgress ? (
                            <Spinner
                              style={{
                                height: '16px',
                                width: '16px',
                                margin: '0 4px',
                              }}
                            />
                          ) : (
                            pages
                          )
                        }
                        iconPosition="right"
                        onClick={() => {
                          setWaybillInProgress(true)
                          getLabel('WAYBILL')
                          onToggle()
                        }}
                      >
                        {__('Print waybill', 'posten-bring-checkout')}
                      </MenuItem>
                    )}
                    {order.mybring_bookings[0].returnLabelUrl && (
                      <MenuItem
                        icon={
                          returnLabelInProgress ? (
                            <Spinner
                              style={{
                                height: '16px',
                                width: '16px',
                                margin: '0 4px',
                              }}
                            />
                          ) : (
                            undo
                          )
                        }
                        iconPosition="right"
                        onClick={() => {
                          setReturnLabelInProgress(true)
                          getLabel('RETURN')
                          onToggle()
                        }}
                      >
                        {__('Print return label', 'posten-bring-checkout')}
                      </MenuItem>
                    )}
                  </MenuGroup>
                  <MenuGroup label={__('Tracking', 'posten-bring-checkout')}>
                    <MenuItem icon={external} iconPosition="right">
                      <Link
                        href={order.mybring_bookings[0].trackingUrl}
                        openInNewTab={true}
                        tone={'neutral'}
                        variant="unstyled"
                        rel="noreferrer"
                        onClick={() => setMenuOpen(false)}
                      >
                        {__('Tracking', 'posten-bring-checkout')}
                      </Link>
                    </MenuItem>
                  </MenuGroup>
                </>
              )}
            </DropdownMenu>
          </div>
        </div>
      </div>
    </li>
  )
}

export default BookedOrderListItem
