import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import ModuleHeader from 'components/pageItems/ModuleHeader';
import adminConfig from 'config/admin';
import CustomIcon from 'components/items/CustomIcon';
import moment from 'moment';
import styleIdentifiers from './singleOrder.scss';

// Assets
import placeholder from './assets/placeholder.jpg';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type SingleOrderProps = StateProps & DispatchProps & OwnProps;

const CardDisplay = props => {
  const { children, title, size, className } = props;

  return (
    <div className={styles('CardDisplay')}>
      <div className={styles('header')}>
        <div className={styles('title')}>{title}</div>
        {size && <div className={styles('size')}>{size}</div>}
      </div>
      <div className={styles('content', className)}>{children}</div>
    </div>
  );
};

const SingleOrder = (props: SingleOrderProps) => {
  const {
    match: { params },
    orderCancel,
    orderMarkPaid,
    orderMarkUnPaid,
    orderReimburse,
    detail,
  } = props;

  const options = adminConfig?.adminShop?.ressource[params.resource];

  const data = detail?.data;

  const client = data?.contactInfo;

  const cart = data?.lines;

  function getNumberItem() {
    let num = 0;
    for (let index = 0; index < cart.length; index++) {
      const element = cart[index];
      num += element.quantity;
    }
    return num;
  }

  function renderFormattedAdress(address) {
    if (!address) return '-';

    return (
      <>
        <div>{`${address?.street}, ${address?.number}`}</div>
        <div>{address?.city}</div>
        <div>{address?.zip}</div>
        {address?.state && <div>{address?.state}</div>}
        <div>{address?.country}</div>
      </>
    );
  }

  return (
    <div className={styles('SingleOrder')}>
      <ModuleHeader
        title={`${options.titleDetail} - ${moment(data?.createdAt).format('DD/MM/YYYY')}`}
        actions={[
          { label: 'Mark as paid', action: () => orderMarkPaid({ id: params.id }) },
          { label: 'Mark as unpaid', action: () => orderMarkUnPaid({ id: params.id }) },
          { label: 'Reimburse', action: () => orderReimburse({ id: params.id }) },
          { label: 'Cancel Order', action: () => orderCancel({ id: params.id }) },
        ]}
      />
      <div className={styles('container')}>
        <div className={styles('detail')}>
          {cart && (
            <>
              <CardDisplay title="Status">
                <div className={styles('status-container')}>
                  <div className={styles('status-line')}>
                    <div className={styles('title')}>Payment status</div>
                    <div className={styles('status')}>{data?.paymentStatus}</div>
                  </div>
                  <div className={styles('status-line')}>
                    <div className={styles('title')}>Order status</div>
                    <div className={styles('status')}>{data?.orderStatus}</div>
                  </div>
                </div>
              </CardDisplay>
              <CardDisplay title="Articles" size={cart.length}>
                {cart.map((item, key) => (
                  <div key={key} className={styles('article-item')}>
                    <div
                      className={styles('image')}
                      style={{
                        backgroundImage: `url(${(item.getProduct.cover &&
                          item.getProduct.cover.large) ||
                          placeholder})`,
                      }}
                    />
                    <div className={styles('title')}>
                      <TextItem path={item.getProduct.title} />
                    </div>
                    <div className={styles('bold')}>{item.quantity}</div>
                    <div className={styles('bold')}>
                      {item.getProduct.price.toLocaleString(navigator.language, {
                        style: 'currency',
                        currency: item.getProduct.currency || 'EUR',
                      })}
                    </div>
                  </div>
                ))}
              </CardDisplay>
              <CardDisplay title="Payment summary">
                <div className={styles('payment-container')}>
                  <div className={styles('payment-line')}>
                    <div className={styles('title')}>Subtotal</div>
                    <div className={styles('info')}>{`(${getNumberItem()} items)`}</div>
                    <div className={styles('price')}>
                      {data.subTotalPrice.toLocaleString(navigator.language, {
                        style: 'currency',
                        currency: cart[0].getProduct.currency,
                      })}
                    </div>
                  </div>
                  <div className={styles('payment-line')}>
                    <div className={styles('title')}>Delivery</div>
                    <div className={styles('price')}>{0}</div>
                  </div>
                  <div className={styles('payment-line')}>
                    <div className={styles('title')}>Promo</div>
                    {data?.promo && (
                      <div className={styles('info')}>{`code: ${data.promo.code}`}</div>
                    )}
                    <div className={styles('price')}>
                      {data?.promo ? (
                        <>
                          {data.promo.type === 'percentage' && `- ${data.promo.value} %`}
                          {data.promo.type === 'fixed' &&
                            `- ${data.promo.value.toLocaleString(navigator.language, {
                              style: 'currency',
                              currency: cart[0].getProduct.currency,
                            })}`}
                        </>
                      ) : (
                        0
                      )}
                    </div>
                  </div>
                  <div className={styles('payment-line')}>
                    <div className={styles('title')}>Tax</div>
                    <div className={styles('info')}>VAT (included)</div>
                    <div className={styles('price')}>
                      {`+ ${data.vatPrice.toLocaleString(navigator.language, {
                        style: 'currency',
                        currency: cart[0].getProduct.currency,
                      })}`}
                    </div>
                  </div>
                </div>
                <div className={styles('payment-total')}>
                  <div className={styles('title')}>Total</div>
                  <div className={styles('price')}>
                    {data.finalPrice.toLocaleString(navigator.language, {
                      style: 'currency',
                      currency: cart[0].getProduct.currency,
                    })}
                  </div>
                </div>
              </CardDisplay>
            </>
          )}
        </div>
        <div className={styles('client')}>
          {client && (
            <CardDisplay title="Customer informations">
              <div className={styles('client-card')}>
                <div className={styles('name')}>
                  <div className={styles('letter')}>{client.firstName.charAt(0).toUpperCase()}</div>
                  {`${client.firstName} ${client.lastName}`}
                </div>
                <div className={styles('subtitle')}>
                  <TextItem path="Contact informations" />
                </div>
                <div className={styles('infos')}>
                  <div>
                    <CustomIcon className={styles('icon')} icon={['far', 'envelope']} />
                    {client.email}
                  </div>
                  {client.phoneNumber && (
                    <div>
                      <CustomIcon className={styles('icon')} icon="phone" />
                      {client.phoneNumber}
                    </div>
                  )}
                </div>
                {data.contactInfo && (
                  <>
                    <div className={styles('subtitle')}>
                      <TextItem path="Shipping adress" />
                    </div>
                    <div className={styles('formatted-address')}>
                      {renderFormattedAdress(data.contactInfo.address)}
                    </div>
                  </>
                )}
                {data.billingInfo && (
                  <>
                    <div className={styles('subtitle')}>
                      <TextItem path="Billing adress" />
                    </div>
                    <div className={styles('formatted-address')}>
                      {renderFormattedAdress(data.billingInfo.address)}
                    </div>
                  </>
                )}
              </div>
            </CardDisplay>
          )}
        </div>
      </div>
    </div>
  );
};

export default SingleOrder;
