import React, { useEffect, useState } from "react";
import { getSuppliers } from "../api/supplierApi";
import { createShipment, deleteShipment, getShipments, updateShipment } from "../api/shipmentApi";
import Message from "../components/Message";
import PageHeader from "../components/PageHeader";

var emptyShipment = {
  supplier: "",
  shipmentNumber: "",
  shipmentDate: "",
  shipmentStatus: "",
  destination: "",
};

var shipmentStatuses = ["Pending", "In Transit", "Delivered", "Cancelled"];

function formatDateForInput(dateValue) {
  if (!dateValue) return "";
  return new Date(dateValue).toISOString().split("T")[0];
}

function Shipment() {
  var formState = useState(emptyShipment);
  var formData = formState[0];
  var setFormData = formState[1];
  var supplierState = useState([]);
  var suppliers = supplierState[0];
  var setSuppliers = supplierState[1];
  var shipmentState = useState([]);
  var shipments = shipmentState[0];
  var setShipments = shipmentState[1];
  var editingState = useState("");
  var editingId = editingState[0];
  var setEditingId = editingState[1];
  var messageState = useState("");
  var message = messageState[0];
  var setMessage = messageState[1];
  var messageTypeState = useState("");
  var messageType = messageTypeState[0];
  var setMessageType = messageTypeState[1];

  function loadData() {
    return Promise.all([getSuppliers(), getShipments()])
      .then(function (responses) {
        setSuppliers(responses[0].data);
        setShipments(responses[1].data);
      });
  }

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

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

  function clearForm() {
    setFormData(emptyShipment);
    setEditingId("");
  }

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

    var request = editingId ? updateShipment(editingId, formData) : createShipment(formData);

    request
      .then(function (response) {
      setMessageType("success");
      setMessage(response.data.message);
      clearForm();
      loadData();
      })
      .catch(function (error) {
        setMessageType("error");
        setMessage(error.response && error.response.data ? error.response.data.message : "Failed to save shipment");
      });
  }

  function handleEdit(shipment) {
    setEditingId(shipment._id);
    setFormData({
      supplier: shipment.supplier && shipment.supplier._id ? shipment.supplier._id : shipment.supplier,
      shipmentNumber: shipment.shipmentNumber,
      shipmentDate: formatDateForInput(shipment.shipmentDate),
      shipmentStatus: shipment.shipmentStatus,
      destination: shipment.destination,
    });
  }

  function handleDelete(id) {
    if (!confirm("Delete this shipment?")) return;

    deleteShipment(id)
      .then(function (response) {
      setMessageType("success");
      setMessage(response.data.message);
      loadData();
      })
      .catch(function (error) {
        setMessageType("error");
        setMessage(error.response && error.response.data ? error.response.data.message : "Failed to delete shipment");
      });
  }

  return (
    <div>
      <PageHeader title="Shipment" subtitle="Insert, get, update, and delete shipment records" />

      <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">
          <div>
            <label className="mb-2 block text-sm font-semibold">Supplier</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="supplier" value={formData.supplier} onChange={handleChange} required>
              <option value="">Select supplier</option>
              {suppliers.map(function (supplier) {
                return (
                <option key={supplier._id} value={supplier._id}>
                  {supplier.supplierCode} - {supplier.supplierName}
                </option>
                );
              })}
            </select>
          </div>

          <div>
            <label className="mb-2 block text-sm font-semibold">Shipment Number</label>
            <input className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="shipmentNumber" value={formData.shipmentNumber} onChange={handleChange} required />
          </div>

          <div>
            <label className="mb-2 block text-sm font-semibold">Shipment Date</label>
            <input className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="shipmentDate" type="date" value={formData.shipmentDate} onChange={handleChange} required />
          </div>

          <div>
            <label className="mb-2 block text-sm font-semibold">Shipment Status</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="shipmentStatus" value={formData.shipmentStatus} onChange={handleChange} required>
              <option value="">Select status</option>
              {shipmentStatuses.map(function (status) {
                return (
                <option key={status} value={status}>
                  {status}
                </option>
                );
              })}
            </select>
          </div>

          <div className="md:col-span-2">
            <label className="mb-2 block text-sm font-semibold">Destination</label>
            <input className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="destination" value={formData.destination} onChange={handleChange} required />
          </div>
        </div>

        <div className="mt-4 flex flex-wrap gap-2">
          <button className="rounded-md bg-blue-900 px-5 py-2 font-semibold text-slate-50">
            {editingId ? "Update Shipment" : "Insert Shipment"}
          </button>
          {editingId && (
            <button type="button" onClick={clearForm} className="rounded-md border border-blue-900 px-5 py-2 font-semibold">
              Cancel
            </button>
          )}
        </div>
      </form>

      <div className="overflow-x-auto rounded-md border border-slate-200 bg-white">
        <table className="w-full min-w-[900px] text-left text-sm">
          <thead className="bg-blue-900 text-slate-50">
            <tr>
              <th className="p-3">Shipment No</th>
              <th className="p-3">Supplier</th>
              <th className="p-3">Date</th>
              <th className="p-3">Status</th>
              <th className="p-3">Destination</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {shipments.map(function (shipment) {
              return (
              <tr key={shipment._id} className="border-t border-slate-200">
                <td className="p-3">{shipment.shipmentNumber}</td>
                <td className="p-3">{shipment.supplier ? shipment.supplier.supplierName : ""}</td>
                <td className="p-3">{formatDateForInput(shipment.shipmentDate)}</td>
                <td className="p-3">{shipment.shipmentStatus}</td>
                <td className="p-3">{shipment.destination}</td>
                <td className="p-3">
                  <button onClick={function () { handleEdit(shipment); }} className="mr-2 rounded-md border border-blue-900 px-3 py-1 font-semibold">
                    Edit
                  </button>
                  <button onClick={function () { handleDelete(shipment._id); }} className="rounded-md bg-blue-900 px-3 py-1 font-semibold text-slate-50">
                    Delete
                  </button>
                </td>
              </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default Shipment;
