import { FC, useEffect } from 'react';
import { TranslatableAttribute } from 'mystique/components/QuantityList';
import { ComponentRegistry } from 'mystique/registry/ComponentRegistry';
import { ListProps } from 'mystique/components/List';
import { OrderItem } from '../CreateOrder';
import { Card, CardContent, makeStyles, Typography } from '@material-ui/core';
import { useI18n } from 'mystique/hooks/useI18n';
import { TemplateRegistry } from 'mystique/registry/TemplateRegistry';
import { humanifyV2 } from '../../../../../utils/StringUtils';
import { CustomerAddress } from 'interfaces/address';
import { MultiOrder } from './MultiBasketCollection';
import FcCollapsibleText from '../../../../../components/core/FcCollapsibleText';

const productListColumns: TranslatableAttribute[] = [
  // product image
  {
    label: 'fc.se.field.create.order.summary.product.list.head.image',
    labelFallback: 'Image',
    type: 'image',
    value: '{{imageUrl}}',
    options: {
      height: 35,
    },
  },
  // product name
  {
    label: 'fc.se.field.create.order.summary.product.list.head.product',
    labelFallback: 'Product',
    type: 'component',
    options: {
      component: 'fc.attribute.column',
      props: {
        value: [
          {
            name: 'name',
            style: {
              fontSize: '13px',
              wordWrap: 'break-word',
              width: '70px',
            },
          },
          {
            name: 'ref',
            style: {
              color: 'grey',
              fontSize: '13px',
              wordWrap: 'break-word',
              width: '70px',
            },
          },
        ],
      },
    },
  },
  // Price
  {
    label: 'fc.se.field.create.order.summary.product.list.head.price',
    labelFallback: 'Price',
    value:
      '<span style="font-size: 13px">{{currency price prices.0.currency}}</span>',
    align: 'center',
  },
  // Ordered Qty
  {
    label: 'fc.se.field.create.order.summary.product.list.head.quantity',
    labelFallback: 'Quantity',
    value: '{{quantity}}',
    align: 'center',
  },
];

const BasketInformation: FC<BasketInformationProps> = ({
  products,
  orderType,
  deliveryType,
  address,
  price,
  locationRef,
  totalTaxPrice,
  useMultiOrder,
  multiOrder,
  onChange,
}) => {
  const BasketList = ComponentRegistry.get('fc.list') as FC<ListProps>;
  const CardAttribute = ComponentRegistry.get('fc.card.attribute') as FC<any>;

  const { translate } = useI18n();
  const descendants = productListColumns.map((column) => {
    return {
      ...column,
      label: translate(column.label),
    };
  });
  const classes = useStyles();

  const renderCurrency = (value: number, currency: string) =>
    TemplateRegistry.render(`{{currency ${value} '${currency}'}}`);

  useEffect(() => {
    onChange(true, 'summaryPage');

    return () => {
      onChange(false, 'summaryPage');
    };
  }, []);

  return (
    <div className={classes.basketList}>
      {useMultiOrder ? (
        <>
          <Typography variant="h2">
            {translate('fc.se.field.create.order.summary.order.type')}: Multi;
          </Typography>
          <Typography variant="h3">
            {translate('fc.se.field.create.order.summary.order.items')}:
          </Typography>
          {multiOrder?.orderItems.map((item, index) => {
            const deliveryAddress = `${
              multiOrder?.customerAddresses.find(
                (address) => address.ref === item.deliveryAddressRef,
              )?.country || ''
            } ${
              multiOrder?.customerAddresses.find(
                (address) => address.ref === item.deliveryAddressRef,
              )?.state || ''
            } ${
              multiOrder?.customerAddresses.find(
                (address) => address.ref === item.deliveryAddressRef,
              )?.city || ''
            } ${
              multiOrder?.customerAddresses.find(
                (address) => address.ref === item.deliveryAddressRef,
              )?.postcode || ''
            } ${
              multiOrder?.customerAddresses.find(
                (address) => address.ref === item.deliveryAddressRef,
              )?.street || ''
            }`;

            return (
              <Card key={`${item.ref}-${index}`}>
                <CardContent>
                  <Typography variant="h4">{item.ref}</Typography>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate(
                          'fc.se.field.create.order.summary.item.image',
                        )}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">
                        <img
                          alt={item.ref}
                          src={item.imageUrl}
                          className={classes.itemImg}
                        />
                      </Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate(
                          'fc.se.field.create.order.summary.item.name',
                        )}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">{item.name}</Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate('fc.se.field.create.order.summary.quantity')}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">{item.quantity}</Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate('fc.se.field.create.order.summary.price')}:
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">
                        {renderCurrency(item.price, item.prices[0].currency)}
                      </Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate(
                          'fc.se.field.create.order.summary.total.item.price',
                        )}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">
                        {renderCurrency(
                          item.price * item.quantity,
                          item.prices[0].currency,
                        )}
                      </Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate(
                          'fc.se.field.create.order.summary.order.item.type',
                        )}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">
                        {item.orderItemType}
                      </Typography>
                    </div>
                  </div>
                  <div className={classes.productWrapper}>
                    <div className={classes.productProperty}>
                      <Typography variant="body2">
                        {translate(
                          'fc.se.field.create.order.summary.delivery.type',
                        )}
                        :
                      </Typography>
                    </div>
                    <div className={classes.productValue}>
                      <Typography variant="body1">
                        {item.deliveryType}
                      </Typography>
                    </div>
                  </div>
                  {item.orderItemType === 'HD' ? (
                    <div className={classes.productWrapper}>
                      <div className={classes.productProperty}>
                        <Typography variant="body2">
                          {translate(
                            'fc.se.field.create.order.summary.address.label',
                          )}
                          :
                        </Typography>
                      </div>
                      <div className={classes.productValue}>
                        <FcCollapsibleText
                          charCutoff={15}
                          text={deliveryAddress}
                        />
                      </div>
                    </div>
                  ) : (
                    <div className={classes.productWrapper}>
                      <div className={classes.productProperty}>
                        <Typography variant="body2">
                          {translate(
                            'fc.se.field.create.order.summary.pickup.location',
                          )}
                          :
                        </Typography>
                      </div>
                      <div className={classes.productValue}>
                        {item.pickupLocationRef}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </>
      ) : (
        <>
          <BasketList
            attributes={descendants}
            data={products}
            defaultPageSize={10}
            density={{
              toggle: false,
              initial: 'compressed',
            }}
          />
          <CardAttribute
            title={translate(
              'fc.se.field.create.order.summary.delivery.details',
            )}
            variant="outlined"
            attributes={
              address && orderType === 'HD'
                ? [
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.order.type',
                    )}: `,
                    template: orderType,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.delivery.type',
                    )}: `,
                    template: humanifyV2(deliveryType),
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.country',
                    )}: `,
                    template: address.country,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.city',
                    )}: `,
                    template: address.city,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.state',
                    )}: `,
                    template: address.state,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.street',
                    )}: `,
                    template: address.street,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.postcode',
                    )}: `,
                    template: address.postcode,
                  },
                ]
                : locationRef &&
                  orderType === 'CC' && [
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.order.type',
                    )}: `,
                    template: orderType,
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.delivery.type',
                    )}: `,
                    template: humanifyV2(deliveryType),
                  },
                  {
                    label: `${translate(
                      'fc.se.field.create.order.summary.pickup.location',
                    )}: `,
                    template: locationRef,
                  },
                ]
            }
          />
        </>
      )}

      <div className={classes.totalPrice}>
        {!!totalTaxPrice && (
          <Typography align={'right'} component="h4" variant="h4">
            {translate('fc.se.field.create.order.summary.taxes')}:{' '}
            {renderCurrency(totalTaxPrice, products[0]?.prices[0].currency)}
          </Typography>
        )}
        <Typography align={'right'} component="h4" variant="h4">
          {translate('fc.se.field.create.order.summary.subtotal')}:{' '}
          {renderCurrency(
            price,
            products[0]?.prices[0].currency,
          )}
        </Typography>
        <div className={classes.bottom}>
          <Typography align={'right'} component="h3" variant="h3">
            {translate('fc.se.field.create.order.summary.total.price')}:{' '}
            {renderCurrency(
              (price || 0) +
                (totalTaxPrice || 0),
              products[0]?.prices[0].currency,
            )}
          </Typography>
        </div>
      </div>
    </div>
  );
};

interface BasketInformationProps {
  products: OrderItem[];
  orderType: 'HD' | 'CC';
  deliveryType: string;
  price: number;
  onChange: (value: unknown, property: string) => void;
  totalTaxPrice?: number;
  address?: CustomerAddress;
  locationRef?: string;
  useMultiOrder?: boolean;
  multiOrder?: MultiOrder;
}

const useStyles = makeStyles((theme) => ({
  basketList: {
    display: 'flex',
    flexDirection: 'column',
    width: '100%',
    gap: '10px',
    '& *': {
      minWidth: 'auto',
    },
  },
  totalPrice: {
    width: '100%',
    textAlign: 'right',
  },
  productWrapper: {
    display: 'grid',
    gridGap: '10px',
    paddingTop: '0.8em',
    gridTemplateAreas: '"productProperty productValue"',
    gridTemplateColumns: '1fr 2fr',
  },
  productProperty: {
    color: theme.palette.text.secondary,
    gridArea: '"productProperty"',
  },
  productValue: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    gridArea: '"productsValue"',
  },
  itemImg: {
    width: '80px',
  },
  bottom: {
    borderTop: '2px solid #D4D6D8',
  },
}));

export default BasketInformation;
