import React, {useEffect} from "react";
import { useGetOrders, useSetOrder } from "../api";

const sampleOrder =  {
    items: [
      { productName: "B1-14MR", price: 129.99 },
      { productName: "W2C", price: 29.99 },
      { productName: "PSU-24VDC", price: 19.99}
    ],
    totalAmount: 179.97,
    orderDate: "2021-11-22",
    email: "pocketooth@gmail.com",
    orderByFirstName: "John",
    orderByLastName: "Huang",
  };
  
// re-arrange to make invoice detail a self-contained element
const Orders = ({ orderID, setOrderID }) => {
  const orders = useGetOrders(orderID);
  const [results, setOrder] = useSetOrder();

  useEffect(() => {
      if (results.data) {
          let orderID = results.data.setOrderInfo.split(':').pop();
          setOrderID(orderID);
        console.log("results:",orderID)
      }
  }, [results, setOrderID]); //didUpdate

  const onClick = (event) => {
    setOrder(sampleOrder);
    console.log("sample order button clicked");
  };

  let getItems = (order) => {
    return (
      <>
        {order.items?.map((item, index) => {
          return (
            <li key={index}>
              {item.productName} - ${item.price}
            </li>
          );
        })}
      </>
    );
  };

  let MyOrders = () => {
    if (orders) {
      return (
        <table>
          <thead>
            <tr>
              <th></th>
              <th>ID</th>
              <th>items</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((order) => {
              return (
                <tr key={order.orderID}>
                  <td></td>
                  <td>{order.orderID}</td>
                  <td>{getItems(order)}</td>
                  <td>${order.totalAmount}</td>
                </tr>
              );
            })}
          </tbody>
          <tfoot></tfoot>
        </table>
      );
    } else {
      return (
        <>
          <p> Loading... </p>
        </>
      );
    }
  };

  return (
    <div className="container">
      <hr />
      <span className="danger">
        Fetch order list from https://api.oemautomation.com:3001{" "}
      </span>
      <hr />
      <MyOrders />
      <button onClick={onClick}>Call API to add one sample order</button>
      <hr />
    </div>
  );
};

export default Orders;
