import React from 'react';
import { useState, useEffect } from 'react';
import axios from 'axios';

var emptyProduct = { productCode: '', productName: '', quantitySold: '', unitPrice: '' };

function Products(props) {
  var productsState = useState([]);
  var products = productsState[0];
  var setProducts = productsState[1];
  var formState = useState(emptyProduct);
  var form = formState[0];
  var setForm = formState[1];

  var token = props.session ? props.session.token : '';
  var headers = { Authorization: 'Bearer ' + token };

  function load() {
    axios.get(props.API + '/products', { headers: headers })
      .then(function(res) {
        setProducts(res.data);
      })
      .catch(function() {});
  }

  useEffect(function() { load(); }, []);

  function submit() {
    if (!form.productCode || !form.productName || !form.quantitySold || !form.unitPrice) {
      props.setNotice('All fields are required');
      return;
    }
    axios.post(props.API + '/products', {
      productCode: form.productCode,
      productName: form.productName,
      quantitySold: Number(form.quantitySold),
      unitPrice: Number(form.unitPrice)
    }, { headers: headers })
      .then(function() {
        setForm(emptyProduct);
        return load();
      })
      .then(function() {
        props.setNotice('Product saved successfully');
      })
      .catch(function(err) {
        var msg = 'Could not save';
        if (err.response && err.response.data) {
          msg = err.response.data.message || err.response.data.error || msg;
        }
        props.setNotice(msg);
      });
  }

  return (
    <main className="page">
      <div className="page-title"><h2>Products</h2><p>Manage product records.</p></div>
      <section className="form-grid four">
        <input placeholder="Product Code" value={form.productCode} onChange={function(e) { setForm({ productCode: e.target.value, productName: form.productName, quantitySold: form.quantitySold, unitPrice: form.unitPrice }); }} />
        <input placeholder="Product Name" value={form.productName} onChange={function(e) { setForm({ productCode: form.productCode, productName: e.target.value, quantitySold: form.quantitySold, unitPrice: form.unitPrice }); }} />
        <input type="number" placeholder="Quantity Sold" value={form.quantitySold} onChange={function(e) { setForm({ productCode: form.productCode, productName: form.productName, quantitySold: e.target.value, unitPrice: form.unitPrice }); }} />
        <input type="number" placeholder="Unit Price" value={form.unitPrice} onChange={function(e) { setForm({ productCode: form.productCode, productName: form.productName, quantitySold: form.quantitySold, unitPrice: e.target.value }); }} />
        <button onClick={submit}>Submit Data</button>
      </section>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Code</th><th>Name</th><th>Quantity Sold</th><th>Unit Price</th><th>Total</th>
            </tr>
          </thead>
          <tbody>
            {products.length === 0 ? (
              <tr><td colSpan="5" style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>No products found</td></tr>
            ) : products.map(function(p) {
              return (
                <tr key={p._id}>
                  <td>{p.productCode}</td><td>{p.productName}</td>
                  <td>{p.quantitySold}</td><td>{p.unitPrice.toLocaleString()} FRW</td>
                  <td>{(p.quantitySold * p.unitPrice).toLocaleString()} FRW</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </main>
  );
}

export default Products;
