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

var emptySale = { invoiceNumber: '', salesDate: '', paymentMethod: 'Cash', totalAmountPaid: '', customer: '' };

function Sales(props) {
  var salesState = useState([]);
  var sales = salesState[0];
  var setSales = salesState[1];
  var customersState = useState([]);
  var customers = customersState[0];
  var setCustomers = customersState[1];
  var formState = useState(emptySale);
  var form = formState[0];
  var setForm = formState[1];
  var editIdState = useState('');
  var editId = editIdState[0];
  var setEditId = editIdState[1];

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

  function load() {
    Promise.all([
      axios.get(props.API + '/sales', { headers: headers }),
      axios.get(props.API + '/customers', { headers: headers })
    ])
      .then(function(results) {
        setSales(results[0].data);
        setCustomers(results[1].data);
      })
      .catch(function() {});
  }

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

  function submit() {
    if (!form.invoiceNumber || !form.salesDate || !form.paymentMethod || !form.totalAmountPaid || !form.customer) {
      props.setNotice('All fields are required');
      return;
    }
    var payload = {
      invoiceNumber: form.invoiceNumber,
      salesDate: form.salesDate,
      paymentMethod: form.paymentMethod,
      totalAmountPaid: Number(form.totalAmountPaid),
      customer: form.customer
    };

    var request;
    if (editId) {
      request = axios.put(props.API + '/sales/' + editId, payload, { headers: headers });
    } else {
      request = axios.post(props.API + '/sales', payload, { headers: headers });
    }

    request
      .then(function() {
        setForm(emptySale);
        setEditId('');
        props.setNotice(editId ? 'Sale updated successfully' : 'Sale created successfully');
        return load();
      })
      .catch(function(err) {
        var msg = 'Operation failed';
        if (err.response && err.response.data) {
          msg = err.response.data.message || err.response.data.error || msg;
        }
        props.setNotice(msg);
      });
  }

  function edit(sale) {
    setEditId(sale._id);
    setForm({
      invoiceNumber: sale.invoiceNumber,
      salesDate: sale.salesDate ? sale.salesDate.slice(0, 10) : '',
      paymentMethod: sale.paymentMethod,
      totalAmountPaid: String(sale.totalAmountPaid),
      customer: sale.customer ? sale.customer._id : ''
    });
  }

  function remove(id) {
    if (!confirm('Delete this sale?')) return;
    axios.delete(props.API + '/sales/' + id, { headers: headers })
      .then(function() {
        return load();
      })
      .then(function() {
        props.setNotice('Sale deleted successfully');
      })
      .catch(function(err) {
        props.setNotice(err.response && err.response.data ? err.response.data.message : 'Could not delete');
      });
  }

  function dateText(d) {
    return d ? new Date(d).toLocaleDateString() : '-';
  }

  return (
    <main className="page">
      <div className="page-title"><h2>Sales</h2><p>{editId ? 'Edit' : 'Add'} sale record.</p></div>
      <section className="form-grid four">
        <input placeholder="Invoice Number" value={form.invoiceNumber} onChange={function(e) { setForm({ invoiceNumber: e.target.value, salesDate: form.salesDate, paymentMethod: form.paymentMethod, totalAmountPaid: form.totalAmountPaid, customer: form.customer }); }} />
        <input type="date" value={form.salesDate} onChange={function(e) { setForm({ invoiceNumber: form.invoiceNumber, salesDate: e.target.value, paymentMethod: form.paymentMethod, totalAmountPaid: form.totalAmountPaid, customer: form.customer }); }} />
        <select value={form.paymentMethod} onChange={function(e) { setForm({ invoiceNumber: form.invoiceNumber, salesDate: form.salesDate, paymentMethod: e.target.value, totalAmountPaid: form.totalAmountPaid, customer: form.customer }); }}>
          <option>Cash</option><option>Credit Card</option><option>Mobile Money</option><option>Bank Transfer</option>
        </select>
        <input type="number" placeholder="Total Amount" value={form.totalAmountPaid} onChange={function(e) { setForm({ invoiceNumber: form.invoiceNumber, salesDate: form.salesDate, paymentMethod: form.paymentMethod, totalAmountPaid: e.target.value, customer: form.customer }); }} />
        <select value={form.customer} onChange={function(e) { setForm({ invoiceNumber: form.invoiceNumber, salesDate: form.salesDate, paymentMethod: form.paymentMethod, totalAmountPaid: form.totalAmountPaid, customer: e.target.value }); }}>
          <option value="">Select Customer</option>
          {customers.map(function(c) { return React.createElement('option', { key: c._id, value: c._id }, c.firstName + ' ' + c.lastName + ' (' + c.customerNumber + ')'); })}
        </select>
        <button onClick={submit}>{editId ? 'Update' : 'Submit Data'}</button>
        {editId ? React.createElement('button', { className: 'danger', onClick: function() { setForm(emptySale); setEditId(''); } }, 'Cancel') : null}
      </section>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Invoice</th><th>Date</th><th>Customer</th><th>Payment</th><th>Amount</th><th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {sales.length === 0 ? (
              <tr><td colSpan="6" style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>No sales found</td></tr>
            ) : sales.map(function(s) {
              return (
                <tr key={s._id}>
                  <td>{s.invoiceNumber}</td>
                  <td>{dateText(s.salesDate)}</td>
                  <td>{s.customer ? s.customer.firstName + ' ' + s.customer.lastName : 'N/A'}</td>
                  <td>{s.paymentMethod}</td>
                  <td>{s.totalAmountPaid.toLocaleString()} FRW</td>
                  <td>
                    <div className="actions">
                      <button onClick={function() { edit(s); }}>Edit</button>
                      <button className="danger" onClick={function() { remove(s._id); }}>Delete</button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </main>
  );
}

export default Sales;
