import { Price } from '@orderingstack/front-components-price';
import { OrderProductProps } from '../utils/types';
import {
  MainProductNameWrapper,
  MainProductPriceWrapper,
  MainProductQuantityWrapper,
  MainProductWrapper,
} from './style';
import ProductSubItems from '../ProductSubItems';
import Loader from 'react-loader-spinner';
import { PROCESSING } from '@orderingstack/front-components-common';

const OrderProduct = (props: OrderProductProps): JSX.Element => {
  const {
    line,
    fullMode = false,
    showItems = false,
    kdsFilter = '',
    kdsLayout = '',
    currency = '',
  } = props;
  const { product, quantity, price } = line;

  const productLineItems =
    'items' in product &&
    Array.isArray(product.items) &&
    product.items.length > 0 &&
    product.items.map((item: any) => {
      showItems &&
        'items' in item &&
        Array.isArray(item.items) &&
        item.items.map((element: any) => {
          const filteredGroup = element;
          if ('items' in element && Array.isArray(element.items)) {
            const filteredItems = element.items.filter(
              (el: any) => el.extra && el.extra.KDS_FILTER === kdsFilter
            );
            filteredGroup.items = filteredItems;
            return filteredGroup;
          }
          return element;
        });

      return (
        <div key={`${item.id}-item-line`}>
          {item.literals && item.literals.name && (
            <div>{item.literals.name}</div>
          )}
          {Array.isArray(item.items) &&
            item.items.map((item: any) => (
              <ProductSubItems
                key={item.id}
                item={item}
                fullMode={fullMode}
                kdsLayout={kdsLayout}
                currency={currency}
              />
            ))}
        </div>
      );
    });

  return (
    <div>
      <MainProductWrapper>
        <MainProductQuantityWrapper>{quantity} x</MainProductQuantityWrapper>
        <MainProductNameWrapper>
          {product.literals.name}:
        </MainProductNameWrapper>
        <MainProductPriceWrapper>
          <Price amount={price} currency={currency} />
        </MainProductPriceWrapper>
        {line.status === PROCESSING && (
          <Loader type="ThreeDots" color="#000000" height={15} />
        )}
      </MainProductWrapper>

      <div style={{ marginLeft: '30px' }}>{productLineItems}</div>
    </div>
  );
};

export default OrderProduct;
