import React, { useState, useEffect } from "react";
import axios from "axios";
import { frontendConfig } from "../change"; // Points to your updated frontendConfig layout

export default function DynamicPage({ moduleName }) {
  const meta = frontendConfig.structures[moduleName];
  const [records, setRecords] = useState([]);
  const [allData, setAllData] = useState({});
  const [formData, setFormData] = useState({});
  const [editingId, setEditingId] = useState(null);

  // Live stock evaluation helpers
  const [activeAvailableStock, setActiveAvailableStock] = useState(null);

  // --- BUSINESS RULES SCHEMA ISOLATION ---
  const isSalesOrderModule = moduleName === "SalesOrder";
  const isStockInboundModule = moduleName === "StockInbound";

  const fetchState = async () => {
    try {
      const res = await axios.get(`http://localhost:5000/api/data/${moduleName}`);
      setRecords(Array.isArray(res.data) ? res.data : []);
      
      const dataRes = await axios.get("http://localhost:5000/api/data/all");
      setAllData(dataRes.data || {});

      // If a product or batch is currently active in the form, refresh its live badge value too
      if (formData.ProductCode || formData.ProductID) {
        const targetProd = formData.ProductCode || formData.ProductID;
        const freshProduct = dataRes.data["Products"]?.find(p => String(p.ProductCode || "").trim() === String(targetProd || "").trim());
        if (freshProduct) setActiveAvailableStock(Number(freshProduct.CurrentStock || 0));
      }
    } catch (err) {
      console.error("Stock management database synchronization failure:", err);
    }
  };

  useEffect(() => {
    setFormData({});
    setEditingId(null);
    setActiveAvailableStock(null);
    fetchState();
  }, [moduleName]);

  // --- AUTOMATED INVENTORY CALCULATION & STOCK TRACKER ENGINE ---
  const handleInputChange = (key, value) => {
    let updatedForm = { ...formData, [key]: value };

    // A. Operational parameters for Sales Orders (Tracks via Batch Numbers)
    if (isSalesOrderModule && (key === "BatchNumber" || key === "QuantitySold")) {
      const targetBatch = String(updatedForm["BatchNumber"] || "").trim();
      const targetQty = Number(updatedForm["QuantitySold"] || 0);

      if (!targetBatch) {
        updatedForm["TotalCostAmount"] = "";
        setActiveAvailableStock(null);
      } else {
        const activeBatch = allData["StockInbound"]?.find((batch) => {
          const currentBatchStr = String(batch.BatchNumber || "").trim();
          return targetBatch === currentBatchStr || targetBatch.includes(`Batch #${currentBatchStr} `) || targetBatch.startsWith(`Batch #${currentBatchStr}—`);
        });
        
        if (activeBatch) {
          const activeProduct = allData["Products"]?.find(
            (prod) => String(prod.ProductCode || "").trim() === String(activeBatch.ProductCode || "").trim()
          );
          
          if (activeProduct) {
            setActiveAvailableStock(Number(activeProduct.CurrentStock || 0));
            updatedForm["TotalCostAmount"] = Number(activeProduct.UnitPrice || 0) * targetQty;
          } else {
            setActiveAvailableStock(null);
          }
        } else {
          setActiveAvailableStock(null);
        }
      }
    }

    // B. Operational parameters for Stock Inbound
    if (isStockInboundModule && (key === "ProductCode" || key === "ProductID" || key === "product_id")) {
      const targetProductCode = String(value || "").trim();
      if (!targetProductCode) {
        setActiveAvailableStock(null);
      } else {
        const activeProduct = allData["Products"]?.find((prod) => {
          const currentProdStr = String(prod.ProductCode || "").trim();
          return targetProductCode === currentProdStr || targetProductCode.includes(currentProdStr);
        });
        if (activeProduct) {
          setActiveAvailableStock(Number(activeProduct.CurrentStock || 0));
        } else {
          setActiveAvailableStock(null);
        }
      }
    }

    setFormData(updatedForm);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/data/${moduleName}/${meta.pk}/${editingId}`, formData);
      } else {
        if (isSalesOrderModule) {
          const targetBatch = String(formData.BatchNumber || "").trim();
          const activeBatch = allData["StockInbound"]?.find((b) => {
            const currentBatchStr = String(b.BatchNumber || "").trim();
            return targetBatch === currentBatchStr || targetBatch.includes(`Batch #${currentBatchStr} `);
          });
          const activeProduct = allData["Products"]?.find(p => String(p.ProductCode || "").trim() === String(activeBatch?.ProductCode || "").trim());
          
          if (activeProduct && Number(formData.QuantitySold) > Number(activeProduct.CurrentStock || 0)) {
            alert(`Aborted: Outbound request exceeds warehouse availability! (${activeProduct.CurrentStock} units left in stock)`);
            return;
          }
        }
        await axios.post(`http://localhost:5000/api/data/${moduleName}`, formData);
      }
      setFormData({});
      setEditingId(null);
      setActiveAvailableStock(null);
      await fetchState(); // ✅ Pulls the updated auto-calculated stock values instantly
    } catch (err) {
      alert("Action operation failed: " + (err.response?.data?.error || err.message));
    }
  };

  const handleEdit = (row) => {
    setEditingId(row[meta.pk]);
    setFormData({ ...row });
    
    if (isSalesOrderModule && row.BatchNumber) {
      const targetBatch = String(row.BatchNumber || "").trim();
      const activeBatch = allData["StockInbound"]?.find(b => {
        const currentBatchStr = String(b.BatchNumber || "").trim();
        return targetBatch === currentBatchStr || targetBatch.includes(`Batch #${currentBatchStr} `);
      });
      const activeProduct = allData["Products"]?.find(p => String(p.ProductCode || "").trim() === String(activeBatch?.ProductCode || "").trim());
      if (activeProduct) setActiveAvailableStock(Number(activeProduct.CurrentStock || 0));
    }

    if (isStockInboundModule && (row.ProductCode || row.ProductID)) {
      const targetProd = String(row.ProductCode || row.ProductID || "").trim();
      const activeProduct = allData["Products"]?.find(p => {
        const currentProdStr = String(p.ProductCode || "").trim();
        return targetProd === currentProdStr || targetProd.includes(currentProdStr);
      });
      if (activeProduct) setActiveAvailableStock(Number(activeProduct.CurrentStock || 0));
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm("Confirm permanent removal of this stock registry transaction entry?")) return;
    try {
      await axios.delete(`http://localhost:5000/api/data/${moduleName}/${meta.pk}/${id}`);
      fetchState();
    } catch (err) {
      alert(err.response?.data?.error || err.message);
    }
  };

  const renderDropdownOptionLabel = (field, relItem) => {
    if (field.relation === "StockInbound") {
      const associatedProduct = allData["Products"]?.find((p) => String(p.ProductCode || "").trim() === String(relItem.ProductCode || "").trim()) || {};
      return `Batch #${relItem.BatchNumber} — ${associatedProduct.ProductName || "Unknown Product"} (In Stock: ${associatedProduct.CurrentStock || 0})`;
    }
    if (field.relation === "Products") {
      return `${relItem.ProductCode} - ${relItem.ProductName} (Stock: ${relItem.CurrentStock || 0})`;
    }
    if (field.relation === "Suppliers") {
      return `${relItem.SupplierCode} - ${relItem.SupplierName}`;
    }
    return relItem[field.displayField] || relItem[field.valueField];
  };

  return (
    <div className="mx-auto max-w-7xl p-4 sm:p-6 lg:p-8 flex flex-col gap-6 bg-slate-50/50 min-h-screen">
      
      {/* Top Section: Action Registration Input Controls */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-6 relative">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6 border-b border-slate-100 pb-4">
          <div>
            <span className="text-[10px] font-bold uppercase tracking-wider text-indigo-600 bg-indigo-50 px-2.5 py-1 rounded-full">
              Dynamic Stock Management Engine
            </span>
            <h3 className="text-xl font-black text-slate-900 tracking-tight mt-2">
              {editingId ? "Modify Transaction Parameters" : `Log Record Entry: ${moduleName}`}
            </h3>
          </div>
          
          {/* LIVE TOTAL STOCK BADGE INDICATOR */}
          {(isSalesOrderModule || isStockInboundModule) && activeAvailableStock !== null && (
            <div className="flex items-center gap-2 bg-slate-900 text-white rounded-xl px-4 py-2 text-xs shadow-sm">
              <span className="text-slate-400 font-bold uppercase tracking-wider text-[10px]">Current Total Stock:</span>
              <span className={`font-mono font-black text-sm ${activeAvailableStock <= 5 ? "text-rose-400" : "text-emerald-400"}`}>
                {activeAvailableStock} Units
              </span>
            </div>
          )}
        </div>

        <form onSubmit={handleSubmit} className="flex flex-wrap items-end gap-4">
          {meta.fields.map((field) => (
            <div key={field.key} className="flex-1 min-w-[220px] space-y-1.5">
              <label className="block text-xs font-bold tracking-wide text-slate-700 uppercase">
                {field.label}
              </label>
              
              {field.type === "select" ? (
                <div className="relative">
                  <select
                    required
                    value={formData[field.key] || ""}
                    className="w-full rounded-xl border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-slate-900 shadow-sm focus:border-indigo-500 focus:outline-none appearance-none font-medium"
                    onChange={(e) => handleInputChange(field.key, e.target.value)}
                  >
                    <option value="" className="text-slate-400">-- Choose Configuration Option --</option>
                    {allData[field.relation]?.map((relItem) => {
                      const optionValue = relItem[field.valueField];
                      return (
                        <option key={relItem[field.valueField]} value={optionValue}>
                          {renderDropdownOptionLabel(field, relItem)}
                        </option>
                      );
                    })}
                  </select>
                  <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3.5 text-slate-400">
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" /></svg>
                  </div>
                </div>
              ) : (
                <div className="relative">
                  <input
                    type={field.type}
                    required
                    disabled={isSalesOrderModule && field.key === "TotalCostAmount"}
                    value={formData[field.key] || ""}
                    className={`w-full rounded-xl border border-slate-200 px-3.5 py-2.5 text-sm text-slate-900 shadow-sm focus:border-indigo-500 focus:outline-none font-medium ${
                      isSalesOrderModule && field.key === "TotalCostAmount" 
                        ? "bg-slate-50 font-mono font-bold text-emerald-600 cursor-not-allowed border-dashed" 
                        : "bg-white"
                    } ${
                      isSalesOrderModule && field.key === "QuantitySold" && activeAvailableStock !== null && Number(formData.QuantitySold) > activeAvailableStock
                        ? "border-rose-500 text-rose-600 bg-rose-50/30"
                        : ""
                    }`}
                    onChange={(e) => handleInputChange(field.key, e.target.value)}
                    placeholder={field.type === "number" ? "0" : `Provide ${field.label.toLowerCase()}...`}
                  />
                  
                  {isSalesOrderModule && field.key === "QuantitySold" && activeAvailableStock !== null && Number(formData.QuantitySold) > activeAvailableStock && (
                    <span className="text-[10px] text-rose-600 font-bold block mt-1 absolute left-1">
                      ⚠️ Order exceeds available stock!
                    </span>
                  )}
                </div>
              )}
            </div>
          ))}
          
          <div className="w-full sm:w-auto">
            <button 
              type="submit" 
              className="w-full inline-flex justify-center items-center rounded-xl bg-slate-950 px-6 py-2.5 h-[46px] text-sm font-bold text-white shadow-md hover:bg-indigo-600 transition-all whitespace-nowrap"
            >
              {editingId ? "Apply Modifications" : "Save Log Entry"}
            </button>
          </div>
        </form>
      </div>

      {/* Bottom Section: Dynamic Matrix Records Log Table */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
        <div className="p-6 border-b border-slate-100 bg-slate-900 text-white flex justify-between items-center">
          <div>
            <h3 className="font-black tracking-tight text-base">{meta.title || `${moduleName} Management Matrix`}</h3>
            <p className="text-slate-400 text-[11px] mt-0.5">Live warehouse stock index tracker pipeline.</p>
          </div>
          <span className="text-xs bg-slate-800 text-slate-300 font-mono font-bold px-2 py-1 rounded-md">
            Records: {records.length}
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left border-collapse">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-100 text-slate-500 text-[11px] font-bold uppercase tracking-wider">
                <th className="p-4">{meta.pk}</th>
                {meta.fields.filter((f) => f.key !== meta.pk).map((f) => (
                  <th key={`th-${f.key}`} className="p-4">{f.label.replace(/\(.*?\)/g, "")}</th>
                ))}
                {(isStockInboundModule || isSalesOrderModule) && <th key="th-actions-header" className="p-4 text-center">Actions</th>}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {records.length === 0 ? (
                <tr>
                  <td colSpan={meta.fields.length + 2} className="p-12 text-center text-slate-400 font-medium">
                    No active transaction entries found in this stock inventory module registry.
                  </td>
                </tr>
              ) : (
                records.map((row, rowIndex) => {
                  const rowUniqueId = row[meta.pk] || `row-${rowIndex}`;

                  return (
                    <tr key={rowUniqueId} className="hover:bg-slate-50/50 transition-colors font-medium text-slate-700">
                      <td className="p-4 text-slate-900 font-black font-mono bg-slate-50/30">{row[meta.pk]}</td>
                      {meta.fields.filter((f) => f.key !== meta.pk).map((f, colIndex) => (
                        <td key={`cell-${rowUniqueId}-${f.key || colIndex}`} className="p-4">
                          {f.type === "date" ? (
                            <span className="font-mono text-xs">
                              {row[f.key] ? new Date(row[f.key]).toLocaleDateString("en-GB") : "N/A"}
                            </span>
                          ) : f.key === "UnitPrice" || f.key === "TotalCostAmount" || f.key === "TotalCost" ? (
                            <span className="font-bold text-emerald-600 font-mono">{Number(row[f.key] || 0).toLocaleString()} Rwf</span>
                          ) : f.key === "CurrentStock" || f.key === "QuantitySold" || f.key === "QuantityReceived" ? (
                            <span className="font-black font-mono text-slate-900">{row[f.key]}</span>
                          ) : (
                            row[f.key]
                          )}
                        </td>
                      ))}
                      
                      {(isStockInboundModule || isSalesOrderModule) && (
                        <td className="p-4 text-center whitespace-nowrap">
                          <div className="inline-flex rounded-lg shadow-sm bg-white border border-slate-100 p-1 gap-1">
                            <button 
                              onClick={() => handleEdit(row)} 
                              className="rounded-md p-1.5 text-indigo-600 hover:bg-indigo-50 transition-colors text-xs font-bold"
                            >
                              Modify
                            </button>
                            <div className="w-px bg-slate-100 h-5 my-auto" />
                            <button 
                              onClick={() => handleDelete(row[meta.pk])} 
                              className="rounded-md p-1.5 text-rose-600 hover:bg-rose-50 transition-colors text-xs font-bold"
                            >
                              Delete
                            </button>
                          </div>
                        </td>
                      )}
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

    </div>
  );
}