import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Sales() {
  const [products, setProducts] = useState([]);
  const [form, setForm] = useState({ productId: '', qty: '', price: '', date: '' });
  const [stockContext, setStockContext] = useState(null);

  const fetchOperationalMatrix = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/stock');
      setProducts(res.data);
    } catch (err) {
      console.error("Dropdown extraction crash:", err);
    }
  };

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

  const handleProductSelection = (id) => {
    if (!id) {
      setForm({ ...form, productId: '', price: '' });
      setStockContext(null);
      return;
    }
    const match = products.find(p => p.product_id === parseInt(id, 10));
    if (match) {
      setForm(prev => ({ ...prev, productId: id, price: match.unit_price }));
      setStockContext(match.remaining_quantity);
    }
  };

  const handleFormSubmission = async (e) => {
    e.preventDefault();
    if (stockContext !== null && parseInt(form.qty, 10) > stockContext) {
      alert(`Operation Rejected. Only ${stockContext} units available.`);
      return;
    }
    try {
      const res = await axios.post('http://localhost:5000/api/sales', form);
      alert(res.data.message);
      setForm({ productId: '', qty: '', price: '', date: '' });
      setStockContext(null);
      fetchOperationalMatrix();
    } catch (err) {
      alert(err.response?.data?.error || "Transaction failure notification.");
    }
  };

  return (
    <div className="bg-white p-6 md:p-8 rounded-2xl shadow-sm border border-slate-100 max-w-3xl mx-auto px-4">
      <h2 className="text-xl font-bold mb-5 text-slate-800 tracking-tight border-b border-slate-100 pb-3">🛒 Record Sales Outflow Terminal Form</h2>
      <form onSubmit={handleFormSubmission} className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Choose Target Product Item</label>
          <select value={form.productId} className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50 text-sm font-medium outline-none focus:border-indigo-500 transition-all" onChange={e => handleProductSelection(e.target.value)} required>
            <option value="">-- Choose Product From Catalog --</option>
            {products.map(p => (
              <option key={p.product_id} value={p.product_id}>{p.product_name} (Stock Bal: {p.remaining_quantity})</option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Live Stock Registry Context Status</label>
          <input type="text" value={stockContext !== null ? `${stockContext} Units Left in Warehouse` : 'Waiting for selection...'} className={`w-full p-2.5 border rounded-xl text-sm font-bold cursor-not-allowed outline-none ${stockContext === 0 ? 'bg-rose-50 text-rose-600 border-rose-100' : 'bg-slate-100 text-slate-600 border-slate-200'}`} disabled />
        </div>
        <div>
          <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Quantity Disposed (Sold Outflows)</label>
          <input type="number" min="1" value={form.qty} className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50 text-sm font-medium outline-none focus:border-indigo-500" onChange={e => setForm({...form, qty: e.target.value})} required />
        </div>
        <div>
          <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Actual Sold Unit Price (RWF)</label>
          <input type="number" step="0.01" min="0" value={form.price} className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50 text-sm font-medium outline-none focus:border-indigo-500" onChange={e => setForm({...form, price: e.target.value})} required />
        </div>
        <div className="md:col-span-2">
          <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Transaction Execution Calendar Date</label>
          <input type="date" value={form.date} className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50 text-sm font-medium outline-none focus:border-indigo-500" onChange={e => setForm({...form, date: e.target.value})} required />
        </div>
        <button type="submit" disabled={stockContext === 0} className="md:col-span-2 mt-2 bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-200 disabled:cursor-not-allowed text-white font-semibold py-3 rounded-xl shadow-sm transition-all tracking-wide text-sm">
          Execute System Outflow Slip Record
        </button>
      </form>
    </div>
  );
}

// FIXED CRITICAL CRASH: Added standard explicit default hook export
export default Sales;