import { FC, useContext, useEffect } from 'react';
import { makeStyles, Theme } from '@material-ui/core';
import { CreateOrderInterface, OrderItem } from '../CreateOrder';
import _ from 'lodash';
import MultiBasketCollectionItem from './MultiBasketCollectionItem';
import { CreateOrderContext } from '../CreateOrderContext';
import { MultiCustomerAddress } from 'interfaces/address';

export interface MultiOrder {
  orderType: 'multi';
  customerAddresses: MultiCustomerAddress[];
  orderItems: MultiOrderItem[];
}

export interface SplitItem {
  ref: string;
  idx: number;
  quantity: number;
}

export interface MultiOrderItem extends OrderItem {
  orderItemType: 'HD' | 'CC';
  deliveryType: string;
  pickupLocationRef?: string;
  deliveryAddressRef?: string;
  fulfilmentPlanRef?: string;
  fulfilmentRef?: string;
}

interface MultiBasketCollectionProducts {
  onChange: (value: unknown, property: string) => void;
  products: OrderItem[] | MultiOrder;
  multiOrder?: MultiOrder;
}

const MultiBasketCollection: FC<MultiBasketCollectionProducts> = ({
  products,
  multiOrder,
  onChange,
}) => {
  const { createOrderInf, customerAddresses, setCreateOrderInf } = useContext(
    CreateOrderContext,
  );
  const {
    deliveryAddress,
    type: orderType,
    pickupLocationRef,
  } = createOrderInf as CreateOrderInterface;
  const { defaultAddress } = customerAddresses || {};

  const classes = useStyles();

  useEffect(() => {
    if (Array.isArray(products)) {
      const customerAddresses: MultiCustomerAddress[] = [];
      let defaultDeliveryAddressRef: string, defaultCustomerAddressRef: string;
      if (deliveryAddress) {
        defaultDeliveryAddressRef = `Multi-dd-${Math.random() * 100}`;
        customerAddresses.push({
          ref: defaultDeliveryAddressRef,
          ...deliveryAddress,
        });
      }
      if (defaultAddress) {
        defaultCustomerAddressRef = `Multi-dc-${Math.random() * 100}`;
        customerAddresses.push({
          ref: defaultCustomerAddressRef,
          ...defaultAddress,
        });
      }
      const multiOrder: MultiOrder = {
        orderType: 'multi',
        customerAddresses,
        orderItems: (products as OrderItem[]).map((product) => {
          return {
            ...product,
            orderItemType: orderType,
            deliveryType: 'STANDARD',
            deliveryAddressRef:
              defaultDeliveryAddressRef || defaultCustomerAddressRef,
            pickupLocationRef: pickupLocationRef,
          };
        }),
      };
      onChange(multiOrder, 'multiOrder');
    }
  }, [products]);

  const changeMultiOrder = (value: unknown, property?: string) => {
    if (setCreateOrderInf) {
      setCreateOrderInf((prevState: any) => {
        let newMultiOrder: any;
        if (property == undefined) {
          newMultiOrder = value;
        } else if (prevState) {
          newMultiOrder = _.cloneDeep(prevState.multiOrder);
          _.set(newMultiOrder, property, value);
        }

        return {
          ...prevState,
          multiOrder: { ...newMultiOrder },
        };
      });
    }
  };

  const addNewMultiItem = (
    orderItem: MultiOrderItem,
    splitItem: SplitItem | undefined,
  ) => {
    if (multiOrder && splitItem) {
      const copyOrderItem = _.cloneDeep(orderItem);

      copyOrderItem.quantity -= splitItem.quantity;
      const newOrderItem: MultiOrderItem = {
        ...copyOrderItem,
        quantity: splitItem.quantity,
      };

      const newMultiOrder = _.cloneDeep(multiOrder);
      newMultiOrder.orderItems.forEach((item) => {
        item.fulfilmentPlanRef = undefined;
      });

      newMultiOrder.orderItems.splice(splitItem.idx, 1, copyOrderItem);
      newMultiOrder.orderItems.splice(splitItem.idx + 1, 0, newOrderItem);

      onChange(newMultiOrder, 'multiOrder');
    }
  };

  return (
    <div className={classes.fullWidth}>
      {!!multiOrder &&
        multiOrder.orderItems.map((item, idx) => (
          <MultiBasketCollectionItem
            key={idx}
            item={item}
            itemsQuantity={multiOrder.orderItems.length}
            idx={idx}
            changeMultiOrder={changeMultiOrder}
            addNewMultiItem={addNewMultiItem}
          />
        ))}
    </div>
  );
};

const useStyles = makeStyles((theme: Theme) => ({
  fullWidth: {
    width: '100%',
  },
  product: {
    padding: '24px 22px',
    border: `2px solid ${theme.palette.divider}`,
    borderBottom: 'none',
    width: '100%',
    boxSizing: 'border-box',
    position: 'relative',
    '&:last-child': {
      borderBottom: `2px solid ${theme.palette.divider}`,
    },
  },
  productImg: {
    width: '80px',
  },
  productContainer: {
    display: 'flex',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    flexWrap: 'wrap',
  },
  productContainerText: {
    width: '70%',
  },
  productContainerRow: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'flex-start',
    width: '100%',
    gap: '15px',
  },
  productWrapper: {
    display: 'grid',
    alignItems: 'center',
    gridGap: '10px',
    paddingTop: '0.8em',
    gridTemplateAreas: '"productName productValue"',
    gridTemplateColumns: '1fr 2fr',
  },
  productName: {
    color: theme.palette.text.secondary,
    gridArea: '"productName"',
    fontSize: '13px',
  },
  productValue: {
    fontSize: '13px',
    lineHeight: 1.2,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    '& p:nth-of-type(2)': {
      color: '#4CAF50',
    },
  },
  modal: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalRow: {
    display: 'flex',
    alignItems: 'center',
    flexWrap: 'wrap',
  },
  modalButton: {
    marginLeft: 'auto',
    marginTop: '15px',
    display: 'block',
  },
  modalContent: {
    minWidth: '300px',
  },
  modalInput: {
    // minWidth: '300px',
  },
  modalContentAddress: {
    display: 'flex',
    flexDirection: 'column',
    gap: '10px',
    alignItems: 'flex-start',
    minWidth: '300px',
  },
}));

export default MultiBasketCollection;
