import React, { useEffect, useState } from "react";
import { createSupplier, getSuppliers } from "../api/supplierApi";
import Message from "../components/Message";
import PageHeader from "../components/PageHeader";

var emptySupplier = {
  supplierCode: "",
  supplierName: "",
  telephone: "",
  address: "",
  email: "",
};

function Supplier() {
  var formState = useState(emptySupplier);
  var formData = formState[0];
  var setFormData = formState[1];
  var supplierState = useState([]);
  var suppliers = supplierState[0];
  var setSuppliers = supplierState[1];
  var messageState = useState("");
  var message = messageState[0];
  var setMessage = messageState[1];
  var messageTypeState = useState("");
  var messageType = messageTypeState[0];
  var setMessageType = messageTypeState[1];

  function loadSuppliers() {
    return getSuppliers()
      .then(function (response) {
        setSuppliers(response.data);
      });
  }

  useEffect(function () {
    loadSuppliers().catch(function () {});
  }, []);

  function handleChange(event) {
    var newFormData = Object.assign({}, formData);
    newFormData[event.target.name] = event.target.value;
    setFormData(newFormData);
  }

  function handleSubmit(event) {
    event.preventDefault();
    setMessage("");

    createSupplier(formData)
      .then(function (response) {
      setMessageType("success");
      setMessage(response.data.message);
      setFormData(emptySupplier);
      loadSuppliers();
      })
      .catch(function (error) {
        setMessageType("error");
        setMessage(error.response && error.response.data ? error.response.data.message : "Failed to save supplier");
      });
  }

  return (
    <div>
      <PageHeader title="Supplier" subtitle="Insert supplier records only" />

      <form onSubmit={handleSubmit} className="mb-6 rounded-md border border-slate-200 bg-white p-4">
        <Message type={messageType} text={message} />
        <div className="grid gap-4 md:grid-cols-2">
          {Object.keys(emptySupplier).map(function (field) {
            return (
            <div key={field}>
              <label className="mb-2 block text-sm font-semibold">{field}</label>
              <input
                className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900"
                name={field}
                value={formData[field]}
                onChange={handleChange}
                required
                type={field === "email" ? "email" : "text"}
              />
            </div>
            );
          })}
        </div>
        <button className="mt-4 rounded-md bg-blue-900 px-5 py-2 font-semibold text-slate-50">Insert Supplier</button>
      </form>

      <div className="overflow-x-auto rounded-md border border-slate-200 bg-white">
        <table className="w-full min-w-[760px] text-left text-sm">
          <thead className="bg-blue-900 text-slate-50">
            <tr>
              <th className="p-3">Code</th>
              <th className="p-3">Name</th>
              <th className="p-3">Telephone</th>
              <th className="p-3">Address</th>
              <th className="p-3">Email</th>
            </tr>
          </thead>
          <tbody>
            {suppliers.map(function (supplier) {
              return (
              <tr key={supplier._id} className="border-t border-slate-200">
                <td className="p-3">{supplier.supplierCode}</td>
                <td className="p-3">{supplier.supplierName}</td>
                <td className="p-3">{supplier.telephone}</td>
                <td className="p-3">{supplier.address}</td>
                <td className="p-3">{supplier.email}</td>
              </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default Supplier;
