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

function StockStatus() {
  const [products, setProducts] = useState([]);
  const [stockList, setStockList] = useState([]);
  const [form, setForm] = useState({ productId: '', available: 0, sold: 0 });
  const [editingId, setEditingId] = useState(null);
  
  // Real-time search filter state
  const [searchTerm, setSearchTerm] = useState('');

  // Load structural updates from unified backend router channels
  const loadDataMatrix = async () => {
    try {
      const stockRes = await axios.get('http://localhost:5000/api/stock');
      setProducts(stockRes.data);
      setStockList(stockRes.data);
    } catch (err) {
      console.error("Ledger extraction error:", err);
    }
  };

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

  // Handle dropdown changes and auto-populate values straight from database row contexts
  const handleProductSelection = (e) => {
    const selectedId = e.target.value;
    
    if (!selectedId) {
      setForm({ productId: '', available: 0, sold: 0 });
      return;
    }

    // Locate matching metrics inside the loaded products data matrix array
    const matchedProduct = products.find(p => String(p.product_id) === String(selectedId));
    
    if (matchedProduct) {
      setForm({
        productId: selectedId,
        available: matchedProduct.stored_quantity ?? 0,
        sold: matchedProduct.sold_quantity ?? 0
      });
    } else {
      setForm({ productId: selectedId, available: 0, sold: 0 });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!form.productId) {
      return alert("Target item selection is required.");
    }

    // Explicit numeric schema enforcement formatting
    const payload = {
      productId: parseInt(form.productId, 10),
      available: parseInt(form.available, 10) || 0,
      sold: parseInt(form.sold, 10) || 0
    };

    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/stock/${editingId}`, payload);
        alert('Stock updates executed successfully.');
        setEditingId(null);
      } else {
        await axios.post('http://localhost:5000/api/stock', payload);
        alert('New stock entry initialized successfully.');
      }
      // Return parameters to a clean base structure
      setForm({ productId: '', available: 0, sold: 0 });
      loadDataMatrix();
    } catch (err) {
      alert('Operation rejected by backend validation rules.');
    }
  };

  const handleEdit = (item) => {
    setEditingId(item.stock_id);
    setForm({ 
      productId: item.product_id || '', 
      available: item.stored_quantity ?? 0, 
      sold: item.sold_quantity ?? 0 
    });
  };

  const handleDelete = async (id) => {
    if (window.confirm("Are you sure you want to drop this stock parameters record row?")) {
      try {
        await axios.delete(`http://localhost:5000/api/stock/${id}`);
        loadDataMatrix();
      } catch (err) {
        alert("Failed to delete stock row assignment.");
      }
    }
  };

  // --- CSV DOWNLOAD EXPORT ENGINE ---
  const handleDownloadCSV = () => {
    const headers = ['Product Descriptor', 'Stored Stock', 'Sold Outflows', 'Live Balance'];
    
    const rows = filteredStockList.map(item => [
      item.product_name,
      item.stored_quantity,
      item.sold_quantity,
      item.remaining_quantity
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(val => `"${String(val).replace(/"/g, '""')}"`).join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `Stock_Status_Matrix_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // Filter items in real time based on the search query
  const filteredStockList = stockList.filter(item => 
    (item.product_name || '').toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6 max-w-6xl mx-auto px-4 py-2">
      
      {/* Dynamic Form Controller Section */}
      <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
        <h2 className="text-xl font-bold mb-4 text-slate-800 tracking-tight">
          {editingId ? '⚠️ Edit Warehouse Parameters Matrix' : '📦 Initialize Stock Adjustments Log'}
        </h2>
        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
          <div>
            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">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 disabled:opacity-60 text-slate-800" 
              onChange={handleProductSelection} 
              disabled={!!editingId} 
              required
            >
              <option value="">-- Select Product --</option>
              {products.map(p => (
                <option key={p.product_id} value={p.product_id}>
                  {p.product_name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Stored (Available) Quantity Base</label>
            <input 
              type="number" 
              min="0" 
              value={form.available ?? 0} 
              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, available: e.target.value})} 
              required 
            />
          </div>
          <div>
            <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Sold Quantity Counter Metric</label>
            <input 
              type="number" 
              min="0" 
              value={form.sold ?? 0} 
              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, sold: e.target.value})} 
              required 
            />
          </div>
          <button 
            type="submit" 
            className={`md:col-span-3 w-full font-semibold py-2.5 rounded-xl transition-all tracking-wide text-sm text-white ${editingId ? 'bg-amber-500 hover:bg-amber-600' : 'bg-indigo-600 hover:bg-indigo-700'}`}
          >
            {editingId ? 'Apply Warehouse Stock Correction Updates' : 'Commit Stock Parameter Updates'}
          </button>
        </form>
      </div>

      {/* Main Table Inventory Visualization Section */}
      <div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
        <div className="p-4 border-b border-slate-100 bg-slate-50/50 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          <h3 className="font-bold text-slate-800 text-sm">System Live Stock Registry Matrix Balance</h3>
          
          {/* Controls Layer: Search Input and Export Trigger */}
          <div className="flex items-center gap-2">
            <input 
              type="text"
              placeholder="Search stock descriptor..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="p-2 border border-slate-200 text-xs rounded-xl outline-none focus:border-indigo-500 w-48 font-medium bg-white"
            />
            <button 
              onClick={handleDownloadCSV}
              className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs px-3 py-2 rounded-xl flex items-center gap-1 shadow-sm transition-all"
            >
              📥 Export CSV
            </button>
          </div>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-100 text-xs font-bold text-slate-500 uppercase tracking-wider">
                <th className="p-4">Product Descriptor</th>
                <th className="p-4">Stored Stock</th>
                <th className="p-4">Sold Outflows</th>
                <th className="p-4">Live Balance</th>
                <th className="p-4 text-center">Lifecycle Action</th>
              </tr>
            </thead>
            <tbody className="text-sm divide-y divide-slate-100 text-slate-700">
              {filteredStockList.length === 0 ? (
                <tr>
                  <td colSpan="5" className="text-center p-6 text-slate-400 italic">
                    No matching inventory registry metrics found.
                  </td>
                </tr>
              ) : filteredStockList.map(item => {
                const remaining = item.remaining_quantity ?? 0;
                return (
                  <tr key={item.product_id} className="hover:bg-slate-50/50 transition-colors">
                    <td className="p-4 font-semibold text-slate-900">{item.product_name}</td>
                    <td className="p-4 font-mono font-semibold text-blue-600">{item.stored_quantity} Units</td>
                    <td className="p-4 font-mono font-semibold text-amber-600">{item.sold_quantity} Units</td>
                    <td className="p-4">
                      <span className={`px-2.5 py-1 rounded-md font-mono font-bold text-xs ${remaining <= 3 ? 'bg-rose-50 text-rose-600 border border-rose-100' : 'bg-emerald-50 text-emerald-700'}`}>
                        {remaining} Available
                      </span>
                    </td>
                    <td className="p-4 text-center space-x-1.5">
                      {item.stock_id && item.stock_id !== 0 ? (
                        <>
                          <button onClick={() => handleEdit(item)} className="bg-amber-500 hover:bg-amber-600 text-white px-3 py-1 rounded-lg text-xs font-bold shadow-sm transition-all">Edit</button>
                          <button onClick={() => handleDelete(item.stock_id)} className="bg-rose-500 hover:bg-rose-600 text-white px-3 py-1 rounded-lg text-xs font-bold shadow-sm transition-all">Delete</button>
                        </>
                      ) : (
                        <span className="text-xs text-slate-400 italic font-medium">Auto Dynamic Mode</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

    </div>
  );
}

export default StockStatus;