import React, { useEffect, useState } from "react";
import { createWarehouse, getWarehouses } from "../api/warehouseApi";
import Layout from "../components/Layout";
import Message from "../components/Message";

const WarehousePage = ({ user, setUser }) => {
  const initialForm = {
    warehouseCode: "",
    warehouseName: "",
    warehouseLocation: ""
  };
  const [formData, setFormData] = useState(initialForm);
  const [warehouses, setWarehouses] = useState([]);
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");

  const loadWarehouses = async () => {
    const data = await getWarehouses();
    setWarehouses(data);
  };

  useEffect(() => {
    loadWarehouses();
  }, []);

  const handleChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (Object.values(formData).some((value) => value === "")) {
      setMessageType("error");
      setMessage("All warehouse fields are required");
      return;
    }

    try {
      const data = await createWarehouse(formData);
      setMessageType("success");
      setMessage(data.message);
      setFormData(initialForm);
      loadWarehouses();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  return (
    <Layout title="Warehouse" user={user} setUser={setUser}>
      <form onSubmit={handleSubmit} className="rounded-md border border-primary p-4">
        <Message message={message} type={messageType} />
        <div className="grid gap-4 md:grid-cols-3">
          <input name="warehouseCode" placeholder="Warehouse Code" value={formData.warehouseCode} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="warehouseName" placeholder="Warehouse Name" value={formData.warehouseName} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="warehouseLocation" placeholder="Warehouse Location" value={formData.warehouseLocation} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
        </div>
        <button className="mt-4 rounded-md bg-primary px-5 py-3 font-semibold text-secondary">Save Warehouse</button>
      </form>

      <div className="mt-6 overflow-x-auto">
        <table className="w-full min-w-[560px] border border-primary text-left text-sm">
          <thead className="bg-primary text-secondary">
            <tr>
              <th className="p-3">Code</th>
              <th className="p-3">Name</th>
              <th className="p-3">Location</th>
            </tr>
          </thead>
          <tbody>
            {warehouses.length === 0 ? (
              <tr className="border-t border-primary">
                <td colSpan="3" className="p-3 text-center">No warehouses recorded</td>
              </tr>
            ) : (
              warehouses.map((warehouse) => (
                <tr key={warehouse._id} className="border-t border-primary">
                  <td className="p-3">{warehouse.warehouseCode}</td>
                  <td className="p-3">{warehouse.warehouseName}</td>
                  <td className="p-3">{warehouse.warehouseLocation}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Layout>
  );
};

export default WarehousePage;
