import React, { useEffect, useState } from "react";
import { getProducts } from "../api/productApi";
import { getWarehouses } from "../api/warehouseApi";
import {
  createTransaction,
  deleteTransaction,
  getTransactions,
  updateTransaction
} from "../api/transactionApi";
import Layout from "../components/Layout";
import Message from "../components/Message";

const TransactionPage = ({ user, setUser }) => {
  const initialForm = {
    product: "",
    warehouse: "",
    transactionDate: "",
    quantityMoved: "",
    transactionType: "Stock In"
  };
  const [formData, setFormData] = useState(initialForm);
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [transactions, setTransactions] = useState([]);
  const [editingId, setEditingId] = useState("");
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");

  const loadData = async () => {
    const [productData, warehouseData, transactionData] = await Promise.all([
      getProducts(),
      getWarehouses(),
      getTransactions()
    ]);

    setProducts(productData);
    setWarehouses(warehouseData);
    setTransactions(transactionData);
  };

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

  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 transaction fields are required");
      return;
    }

    try {
      const data = editingId
        ? await updateTransaction(editingId, formData)
        : await createTransaction(formData);

      setMessageType("success");
      setMessage(data.message);
      setFormData(initialForm);
      setEditingId("");
      loadData();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  const startEdit = (transaction) => {
    setEditingId(transaction._id);
    setFormData({
      product: transaction.product?._id || "",
      warehouse: transaction.warehouse?._id || "",
      transactionDate: transaction.transactionDate?.slice(0, 10) || "",
      quantityMoved: transaction.quantityMoved,
      transactionType: transaction.transactionType
    });
    setMessage("");
  };

  const cancelEdit = () => {
    setEditingId("");
    setFormData(initialForm);
  };

  const handleDelete = async (id) => {
    const confirmed = window.confirm("Delete this transaction?");

    if (!confirmed) {
      return;
    }

    try {
      const data = await deleteTransaction(id);
      setMessageType("success");
      setMessage(data.message);
      loadData();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  return (
    <Layout title="Transactions" 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-2 lg:grid-cols-5">
          <select name="product" value={formData.product} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            <option value="">Select Product</option>
            {products.map((product) => (
              <option key={product._id} value={product._id}>
                {product.productCode} - {product.productName}
              </option>
            ))}
          </select>

          <select name="warehouse" value={formData.warehouse} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            <option value="">Select Warehouse</option>
            {warehouses.map((warehouse) => (
              <option key={warehouse._id} value={warehouse._id}>
                {warehouse.warehouseCode} - {warehouse.warehouseName}
              </option>
            ))}
          </select>

          <input name="transactionDate" type="date" value={formData.transactionDate} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="quantityMoved" type="number" min="1" placeholder="Quantity Moved" value={formData.quantityMoved} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <select name="transactionType" value={formData.transactionType} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            <option value="Stock In">Stock In</option>
            <option value="Stock Out">Stock Out</option>
          </select>
        </div>

        <div className="mt-4 flex flex-col gap-3 sm:flex-row">
          <button className="rounded-md bg-primary px-5 py-3 font-semibold text-secondary">
            {editingId ? "Update Transaction" : "Save Transaction"}
          </button>
          {editingId && (
            <button type="button" onClick={cancelEdit} className="rounded-md border border-primary px-5 py-3 font-semibold">
              Cancel
            </button>
          )}
        </div>
      </form>

      <div className="mt-6 overflow-x-auto">
        <table className="w-full min-w-[900px] border border-primary text-left text-sm">
          <thead className="bg-primary text-secondary">
            <tr>
              <th className="p-3">Date</th>
              <th className="p-3">Product</th>
              <th className="p-3">Warehouse</th>
              <th className="p-3">Quantity</th>
              <th className="p-3">Type</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {transactions.length === 0 ? (
              <tr className="border-t border-primary">
                <td colSpan="6" className="p-3 text-center">No transactions recorded</td>
              </tr>
            ) : (
              transactions.map((transaction) => (
                <tr key={transaction._id} className="border-t border-primary">
                  <td className="p-3">{transaction.transactionDate?.slice(0, 10)}</td>
                  <td className="p-3">{transaction.product?.productName}</td>
                  <td className="p-3">{transaction.warehouse?.warehouseName}</td>
                  <td className="p-3">{transaction.quantityMoved}</td>
                  <td className="p-3">{transaction.transactionType}</td>
                  <td className="flex gap-2 p-3">
                    <button onClick={() => startEdit(transaction)} className="rounded-md border border-primary px-3 py-2 font-semibold">
                      Edit
                    </button>
                    <button onClick={() => handleDelete(transaction._id)} className="rounded-md bg-primary px-3 py-2 font-semibold text-secondary">
                      Delete
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Layout>
  );
};

export default TransactionPage;
