import React, { useEffect, useState } from "react";
import { createDelivery, deleteDelivery, getDeliveries, updateDelivery } from "../api/deliveryApi";
import { getShipments } from "../api/shipmentApi";
import Message from "../components/Message";
import PageHeader from "../components/PageHeader";

var emptyDelivery = {
  shipment: "",
  deliveryCode: "",
  deliveryDate: "",
  quantityDelivered: "",
  deliveryStatus: "",
};

var deliveryStatuses = ["Pending", "Partial", "Completed", "Returned"];

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

function Delivery() {
  var formState = useState(emptyDelivery);
  var formData = formState[0];
  var setFormData = formState[1];
  var shipmentState = useState([]);
  var shipments = shipmentState[0];
  var setShipments = shipmentState[1];
  var deliveryState = useState([]);
  var deliveries = deliveryState[0];
  var setDeliveries = deliveryState[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([getShipments(), getDeliveries()])
      .then(function (responses) {
        setShipments(responses[0].data);
        setDeliveries(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(emptyDelivery);
    setEditingId("");
  }

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

    var request = editingId ? updateDelivery(editingId, formData) : createDelivery(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 delivery");
      });
  }

  function handleEdit(delivery) {
    setEditingId(delivery._id);
    setFormData({
      shipment: delivery.shipment && delivery.shipment._id ? delivery.shipment._id : delivery.shipment,
      deliveryCode: delivery.deliveryCode,
      deliveryDate: formatDateForInput(delivery.deliveryDate),
      quantityDelivered: delivery.quantityDelivered,
      deliveryStatus: delivery.deliveryStatus,
    });
  }

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

    deleteDelivery(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 delivery");
      });
  }

  return (
    <div>
      <PageHeader title="Delivery" subtitle="Insert, get, update, and delete delivery 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">Shipment</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="shipment" value={formData.shipment} onChange={handleChange} required>
              <option value="">Select shipment</option>
              {shipments.map(function (shipment) {
                return (
                <option key={shipment._id} value={shipment._id}>
                  {shipment.shipmentNumber} - {shipment.destination}
                </option>
                );
              })}
            </select>
          </div>

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

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

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

          <div className="md:col-span-2">
            <label className="mb-2 block text-sm font-semibold">Delivery Status</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" name="deliveryStatus" value={formData.deliveryStatus} onChange={handleChange} required>
              <option value="">Select status</option>
              {deliveryStatuses.map(function (status) {
                return (
                <option key={status} value={status}>
                  {status}
                </option>
                );
              })}
            </select>
          </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 Delivery" : "Insert Delivery"}
          </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">Delivery Code</th>
              <th className="p-3">Shipment</th>
              <th className="p-3">Date</th>
              <th className="p-3">Quantity</th>
              <th className="p-3">Status</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {deliveries.map(function (delivery) {
              return (
              <tr key={delivery._id} className="border-t border-slate-200">
                <td className="p-3">{delivery.deliveryCode}</td>
                <td className="p-3">{delivery.shipment ? delivery.shipment.shipmentNumber : ""}</td>
                <td className="p-3">{formatDateForInput(delivery.deliveryDate)}</td>
                <td className="p-3">{delivery.quantityDelivered}</td>
                <td className="p-3">{delivery.deliveryStatus}</td>
                <td className="p-3">
                  <button onClick={function () { handleEdit(delivery); }} className="mr-2 rounded-md border border-blue-900 px-3 py-1 font-semibold">
                    Edit
                  </button>
                  <button onClick={function () { handleDelete(delivery._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 Delivery;
