import React, { useState } from 'react'
import { Button, Card, CardBody, TextControl } from '@wordpress/components'
import HowTo from './HowTo'
import { ExpandableInfoSection } from './components/ExpandableInfoSection'
import { useI18n } from '@wordpress/react-i18n'
import { closeSmall, Icon, search } from '@wordpress/icons'
import productMetafield from '../../assets/img/product-metafield.png'
import { useEnableWpCompatOverlaySlot } from '@wordpress/ui'

const extractText = (node: React.ReactNode): string => {
  if (typeof node === 'string') {
    return node
  }

  if (Array.isArray(node)) {
    return node.map(extractText).join('')
  }

  if (React.isValidElement(node)) {
    return React.Children.toArray(node.props.children).map(extractText).join('')
  }

  return ''
}

const Faq = () => {
  const { __ } = useI18n()
  useEnableWpCompatOverlaySlot()
  const [searchQuery, setSearchQuery] = useState('')

  const topics = [
    {
      title: __('Customs', 'posten-bring-checkout'),
      content: (
        <>
          {__(
            'Posten Bring Checkout will follow the current rules for customs. To read up on how customs work, you can use the following pages:',
            'posten-bring-checkout'
          )}
          <ul>
            <li>
              <a
                href={__(
                  'https://www.bring.no/en/services/customs',
                  'posten-bring-checkout'
                )}
                target="_blank"
                rel="noreferrer"
              >
                {__('Customs portal - bring.no/en', 'posten-bring-checkout')}
              </a>
            </li>
            <li>
              <a
                href={__(
                  'https://www.bring.com/resources/mybring/order-parcels-with-customs-information',
                  'posten-bring-checkout'
                )}
                target="_blank"
                rel="noreferrer"
              >
                {__(
                  'How to order parcels with customs information in Mybring',
                  'posten-bring-checkout'
                )}
              </a>
            </li>
          </ul>
          <p>
            {__(
              'When you order transport via Posten Bring Checkout in WooCommerce, you will be asked to fill in the necessary PDF files that must be included in your shipment.',
              'posten-bring-checkout'
            )}{' '}
            <a
              href={__(
                'https://www.bring.no/en/services/customs/commercial-invoice-proforma-invoice',
                'posten-bring-checkout'
              )}
              target="_blank"
              rel="noreferrer"
            >
              {__(
                'Difference between a commercial invoice and a proforma invoice',
                'posten-bring-checkout'
              )}
            </a>
            {'. '}
            {__(
              'Costs will be reflected in your invoice.',
              'posten-bring-checkout'
            )}
          </p>
          <p>
            {__(
              'If you have questions about customs, you can contact customer service.',
              'posten-bring-checkout'
            )}
          </p>
        </>
      ),
    },
    {
      title: __('Returns', 'posten-bring-checkout'),
      content: (
        <>
          <strong>
            {__('For Norwegian webshops:', 'posten-bring-checkout')}
          </strong>
          <p>
            {__(
              'When you generate a label for your shipment, we will always include a return label. You can print out and include the return label with the delivery to the customer.',
              'posten-bring-checkout'
            )}
          </p>
          <p>
            {__(
              'If the end-customer wishes to return an item, the end-customer uses the return label & returns the item to the nearest postal drop-off point (post in store or post office). You will not be charged unless the return label is used by your end-customer.',
              'posten-bring-checkout'
            )}
          </p>
          <strong>
            {__(
              'For Swedish/Danish webshops and Norwegian webshops that carry out cross-border shipments:',
              'posten-bring-checkout'
            )}
          </strong>
          <p>
            {__(
              'Your end customer must notify the webshop if they wish to make a return. You have to book transport and generate a label for the return shipment in Mybring.',
              'posten-bring-checkout'
            )}
          </p>
        </>
      ),
    },
    {
      title: __(
        'Customer complaints related to transportation',
        'posten-bring-checkout'
      ),
      content: (
        <>
          <p>
            {__(
              'The customer service feature in Mybring lets you create cases in a quick and clear way. You can also call our customer service: +47 04045 (Norway), +46 770-11 33 00 (Sweden), +45 70203040 (Denmark), or chat with them on Bring.no/Bring.dk/Bring.se.',
              'posten-bring-checkout'
            )}
          </p>
          <p>
            {__(
              'Mybring contains all cases linked to your customer number, whether they are reported by phone, email, bring.no or mybring.com.',
              'posten-bring-checkout'
            )}
          </p>
          <p>
            {__(
              "NB: You need access to customer service in Mybring. if you are the “Administrator” you can grant yourself or your employees' access by following",
              'posten-bring-checkout'
            )}{' '}
            <a
              href={__(
                'https://www.bring.com/resources/mybring/grant-and-change-user-access',
                'posten-bring-checkout'
              )}
              target="_blank"
              rel="noreferrer"
            >
              {__('these steps', 'posten-bring-checkout')}
            </a>
            {', '}
            {__(
              'else you can follow these steps to',
              'posten-bring-checkout'
            )}{' '}
            <a
              href={__(
                'https://www.bring.com/resources/mybring/request-other-accesses',
                'posten-bring-checkout'
              )}
              target="_blank"
              rel="noreferrer"
            >
              {__('request access', 'posten-bring-checkout')}
            </a>
          </p>
        </>
      ),
    },
    {
      title: __('Available services', 'posten-bring-checkout'),
      content: (
        <>
          {__(
            'Posten Bring Checkout includes the following B2C Services:',
            'posten-bring-checkout'
          )}
          <br />
          <br />
          <strong>
            {__('For Norwegian domestic shipments', 'posten-bring-checkout')}
          </strong>
          <ul>
            <li>{__('Mailbox parcel', 'posten-bring-checkout')}</li>
            <li>
              {' '}
              {__(
                'Pick-up parcel (including parcel locker)',
                'posten-bring-checkout'
              )}
            </li>
            <li>{__('Home delivery parcel', 'posten-bring-checkout')}</li>
          </ul>
          <strong>
            {__(
              'For domestic shipments in Sweden/Denmark and cross-border shipments, the following services are available:',
              'posten-bring-checkout'
            )}
          </strong>
          <ul>
            <li>
              {' '}
              {__(
                'Home Delivery Parcel. For cross-border shipments to/from Norway, the service requires the webshop to have a bulk agreement in Mybring (contact customer service in Mybring to set up the agreement)',
                'posten-bring-checkout'
              )}
            </li>
            <li>
              {__(
                'PickUp Parcel (including parcel locker)',
                'posten-bring-checkout'
              )}
            </li>
            <li>
              {__(
                'PickUp Parcel Bulk. This service requires a separate agreement in Mybring (contact customer service in Mybring to set up the agreement). PickUp Parcel Bulk is used to send several parcels together to the same country. For your end customer, this service is equivalent to PickUp Parcel.',
                'posten-bring-checkout'
              )}
            </li>
          </ul>

          {__(
            'The language & service names used in the Checkout towards the end customer will be in Norwegian/Swedish/Danish.',
            'posten-bring-checkout'
          )}
        </>
      ),
    },
    {
      title: __('Order Pick-up from Bring', 'posten-bring-checkout'),
      content: (
        <>
          <p>
            {__(
              "You can order pickup through Mybring. You do this by clicking on Booking in Mybring's landing page, then you choose",
              'posten-bring-checkout'
            )}{' '}
            <a
              href={__(
                'https://www.mybring.com/order/pickup?pickupCountry=NO',
                'posten-bring-checkout'
              )}
              target="_blank"
              rel="noreferrer"
            >
              {__('New pickup', 'posten-bring-checkout')}
            </a>
            {__(
              ' in the sidebar. Fill in your postal code and choose the address & date that suits you.',
              'posten-bring-checkout'
            )}
          </p>
          <p>
            {__(
              'If you want to establish a regular pickup agreement, you can contact customer service.',
              'posten-bring-checkout'
            )}
          </p>
        </>
      ),
    },
    {
      title: __(
        'Hide shipping options for selected products in the checkout',
        'posten-bring-checkout'
      ),
      content: (
        <>
          {__(
            'If you sell products which have large dimensions (e.g.skis), your customers might be presented with misleading shipping options in the checkout. You can therefore choose to exclude different shipping options, such as: "Mailbox parcel", "Parcel lockers" or all (Posten Brings) shipping options for some of your products. This can be done by navigating to the product page, click on the relevant product and go to "Posten Bring Checkout – Shipping settings".',
            'posten-bring-checkout'
          )}
          <div className="mbm mtm">
            <img className="how-to-image" src={productMetafield} alt={''} />
          </div>
          <br />
          <br />
        </>
      ),
    },
  ]

  const filteredTopics = topics.filter(
    topic =>
      topic.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      extractText(topic.content)
        .toLowerCase()
        .includes(searchQuery.toLowerCase())
  )

  const handleClear = () => {
    setSearchQuery('')
  }

  return (
    <div id={'faq-container'}>
      <h1>{__('Frequently Asked Questions', 'posten-bring-checkout')}</h1>
      <hr />
      <Card className="card-section mtm">
        <CardBody className="pam">
          <h3 className="mas">
            {__('General usage', 'posten-bring-checkout')}
          </h3>
          <HowTo />
        </CardBody>
      </Card>

      <Card className="card-section mtm">
        <CardBody className="pam">
          <h3 className="mas">{__('Other topics', 'posten-bring-checkout')}</h3>

          <div className="search-container flex justify-cc align-ic">
            <div className="search-input-wrapper plxs prxs">
              <span className="search-icon">
                <Icon icon={search} />
              </span>
              <TextControl
                value={searchQuery}
                onChange={value => setSearchQuery(value)}
                placeholder={__('Search', 'posten-bring-checkout')}
                autoComplete="off"
                className="search-input pt0 pb0"
                id="search-input"
              />
              {searchQuery && (
                <Button
                  className="clear-icon"
                  icon={closeSmall}
                  onClick={handleClear}
                />
              )}
            </div>
          </div>

          {filteredTopics.map((topic, index) => (
            <ExpandableInfoSection
              key={index}
              sectionTitle={<h4 className="mrm">{topic.title}</h4>}
              detailsText={topic.content}
              detailsClassNames="pls prs pbm pbs mlm mtm"
              id={`faq-${index}`}
            />
          ))}
        </CardBody>
      </Card>

      <Card className="card-section mtm">
        <CardBody className="pam">
          {__(
            'For Mybring specific questions, you will find answers to frequently asked questions',
            'posten-bring-checkout'
          )}{' '}
          <a
            href={__(
              'https://www.bring.com/resources/mybring#mybring',
              'posten-bring-checkout'
            )}
            target="_blank"
            rel="noreferrer"
          >
            {__('here', 'posten-bring-checkout')}
          </a>
          {'. '}
          {__(
            'If you can’t find the answer, go to our chatbot which can also forward you to customer service if relevant. For other questions related to this application or in case you want guidance, you are free to contact us on',
            'posten-bring-checkout'
          )}{' '}
          <a
            href={__(
              'mailto:checkout.implementering@posten.no',
              'posten-bring-checkout'
            )}
            target="_blank"
            rel="noreferrer"
          >
            {__('checkout.implementering@posten.no', 'posten-bring-checkout')}
          </a>
        </CardBody>
      </Card>
    </div>
  )
}

export default Faq
