import React, { useEffect, useState } from "react";
import { addStock, getAllProducts, getAllWarehouses, getAllProfiles } from "../api/api";
import { useNavigate } from "react-router-dom";

export default function Stocks() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    async function fetchOptions() {
      try {
        const [pRes, wRes, uRes] = await Promise.all([
          getAllProducts(),
          getAllWarehouses(),
          getAllProfiles(),
        ]);
        setProducts(pRes.data);
        setWarehouses(wRes.data);
        setUsers(uRes.data);
      } catch (error) {
        console.error("Failed to load options", error);
      }
    }
    fetchOptions();
  }, []);

  async function handleSubmit(event) {
    event.preventDefault();
    setLoading(true);

    const formData = {
      TransactionId: Number(event.target.TransactionId.value),
      TransactionDate: event.target.TransactionDate.value || undefined,
      QuantityMoved: Number(event.target.QuantityMoved.value),
      TransactionType: event.target.TransactionType.value,
      UserId: event.target.UserId.value,
      WarehouseCode: event.target.WarehouseCode.value,
      ProductCode: event.target.ProductCode.value,
    };

    try {
      await addStock(formData);
      alert('Stock transaction recorded');
      navigate('/reports');
    } catch (error) {
      alert(error.response?.data?.message || 'Failed to add transaction');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col items-center">
      <h1 className="text-xl font-bold text-gray-800 mb-4 hover:text-olive-600 cursor-pointer">Stock Transaction</h1>
      <div className="bg-white border border-gray-200 rounded-lg p-4 w-full max-w-lg">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Transaction ID</label>
              <input type="number" name="TransactionId" required placeholder="Enter t-Id" className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
              <input type="date" name="TransactionDate" className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500" />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Quantity</label>
              <input type="number" name="QuantityMoved" required placeholder="Enter Quantity Moved" className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
              <select name="TransactionType" required className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500 bg-white">
                <option value="">Select</option>
                <option value="IN">Stock In</option>
                <option value="OUT">Stock Out</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">User</label>
            <select name="UserId" required className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500 bg-white">
              <option value="">Select user</option>
              {users.map((u) => (
                <option key={u._id} value={u.UserId}>{u.UserId} — {u.username}</option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Warehouse</label>
              <select name="WarehouseCode" required className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500 bg-white">
                <option value="">Select warehouse</option>
                {warehouses.map((w) => (
                  <option key={w._id} value={w.WarehouseCode}>{w.WarehouseCode} — {w.WarehouseName}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Product</label>
              <select name="ProductCode" required className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-olive-500 bg-white">
                <option value="">Select product</option>
                {products.map((p) => (
                  <option key={p._id} value={p.ProductCode}>{p.ProductCode} — {p.ProductName}</option>
                ))}
              </select>
            </div>
          </div>

          <button type="submit" className="w-full h-10 bg-olive-600 hover:bg-olive-700 text-white  rounded font-medium ">
            Add
          </button>
        </form>
      </div>
    </div>
  );
}
