import React, { useState } from "react";
import { addWarehouse } from "../api/api";
import { useNavigate } from "react-router-dom";

export default function Warehouse() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

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

    const formData = {
      WarehouseCode: event.target.WarehouseCode.value,
      WarehouseName: event.target.WarehouseName.value,
      WarehouseLocation: event.target.WarehouseLocation.value,
    };

    try {
      await addWarehouse(formData);
      alert('Warehouse added successfully');
      navigate('/transaction');
    } catch (error) {
      alert(error.response?.data?.message || 'Failed to add warehouse');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col items-center">
      <h1 className="text-2xl font-bold text-gray-800 mb-6 hover:text-olive-600 cursor-pointer">Add Warehouse</h1>
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 w-full max-w-lg">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Warehouse Code</label>
            <input type="text" name="WarehouseCode" required placeholder="Enter w-Code" className="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-olive-500 focus:border-olive-500 outline-none transition" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Warehouse Name</label>
            <input type="text" name="WarehouseName" required placeholder="Enter w-Name" className="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-olive-500 focus:border-olive-500 outline-none transition" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Location</label>
            <input type="text" name="WarehouseLocation" required placeholder="Enter w-Location" className="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-olive-500 focus:border-olive-500 outline-none transition" />
          </div>
          <button type="submit"  className="w-full bg-olive-600 hover:bg-olive-700 text-white rounded-lg font-medium h-10">
            Add
          </button>
        </form>
      </div>
    </div>
  );
}