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

export default function Reports() {
  // --- STATE TEMPLATE ALIGNED WITH THE NEW STOCK MANAGEMENT SCHEMA ---
  const [rawDb, setRawDb] = useState({ Suppliers: [], Products: [], StockInbound: [], SalesOrder: [] });
  const [consolidatedLogs, setConsolidatedLogs] = useState([]);
  const [filteredLogs, setFilteredLogs] = useState([]);
  
  // Filtering states
  const [filterType, setFilterType] = useState("all"); 
  const [targetDate, setTargetDate] = useState("");
  
  // Active Invoice panel focus state
  const [selectedInvoice, setSelectedInvoice] = useState(null);

  // Form states for creating a new automated transaction sale
  const [selectedProductCode, setSelectedProductCode] = useState("");
  const [selectedBatchNumber, setSelectedBatchNumber] = useState("");
  const [inputQuantitySold, setInputQuantitySold] = useState(1);
  const [autoCalculatedPrice, setAutoCalculatedPrice] = useState(0);

  const fetchStockReportData = async () => {
    try {
      const res = await axios.get("http://localhost:5000/api/data/all");
      const { Suppliers = [], Products = [], StockInbound = [], SalesOrder = [] } = res.data || {};
      
      setRawDb({ Suppliers, Products, StockInbound, SalesOrder });

      // --- ADVANCED STRUCTURAL CONSOLIDATION LOOP ---
      const consolidated = SalesOrder.map((order) => {
        const inboundBatch = StockInbound.find((b) => Number(b.BatchNumber) === Number(order.BatchNumber)) || {};
        const product = Products.find((p) => p.ProductCode === inboundBatch.ProductCode) || {};
        const supplier = Suppliers.find((s) => s.SupplierCode === inboundBatch.SupplierCode) || {};

        return {
          InvoiceNumber: order.InvoiceNumber,
          SalesDate: order.SalesDate,
          BatchNumber: order.BatchNumber,
          ProductCode: product.ProductCode || "Unknown SKU",
          ProductName: product.ProductName || "Discontinued Inventory Item",
          Category: product.Category || "General",
          UnitPrice: Number(product.UnitPrice || 0),
          SupplierName: supplier.SupplierName || "Direct Factory Procurement",
          QuantitySold: Number(order.QuantitySold || 0),
          TotalCostAmount: Number(order.TotalCostAmount || 0),
          InboundDate: inboundBatch.InboundDate || null
        };
      });

      setConsolidatedLogs(consolidated);
      setFilteredLogs(consolidated); 
    } catch (err) {
      console.error("Stock database consolidation runtime failure:", err);
    }
  };

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

  // --- AUTOMATIC PRICE DETERMINATION ENGINE ---
  useEffect(() => {
    if (!selectedProductCode) {
      setAutoCalculatedPrice(0);
      return;
    }
    const product = rawDb.Products.find(p => p.ProductCode === selectedProductCode);
    if (product) {
      // Calculate total cost based on product unit rate * desired output quantities
      setAutoCalculatedPrice(Number(product.UnitPrice) * Number(inputQuantitySold));
    }
  }, [selectedProductCode, inputQuantitySold, rawDb.Products]);

  // --- TEMPORAL FILTER MATRIX ENGINE ---
  useEffect(() => {
    if (filterType === "all" || !targetDate) {
      setFilteredLogs(consolidatedLogs);
      return;
    }

    const selected = new Date(targetDate);
    if (isNaN(selected.getTime())) {
      setFilteredLogs(consolidatedLogs);
      return;
    }
    selected.setHours(0,0,0,0);

    const filtered = consolidatedLogs.filter((log) => {
      if (!log.SalesDate) return false;
      
      const logDate = new Date(log.SalesDate);
      if (isNaN(logDate.getTime())) return false; 
      logDate.setHours(0,0,0,0);

      if (filterType === "daily") {
        return logDate.getTime() === selected.getTime();
      }

      if (filterType === "weekly") {
        const startOfWeek = new Date(selected);
        const endOfWeek = new Date(selected);
        endOfWeek.setDate(startOfWeek.getDate() + 7);
        return logDate >= startOfWeek && logDate <= endOfWeek;
      }

      if (filterType === "monthly") {
        return (
          logDate.getFullYear() === selected.getFullYear() &&
          logDate.getMonth() === selected.getMonth()
        );
      }
      return true;
    });

    setFilteredLogs(filtered);
  }, [filterType, targetDate, consolidatedLogs]);

  // --- COMPILATION METRICS ---
  const totalRevenueGenerated = filteredLogs.reduce((sum, item) => sum + item.TotalCostAmount, 0);
  const totalUnitsDispatched = filteredLogs.reduce((sum, item) => sum + item.QuantitySold, 0);

  // --- ATOMIC SALES PROCESSING OUTBOUND ORDER METHOD ---
  const handleRegisterSale = async (e) => {
    e.preventDefault();
    if (!selectedBatchNumber || !selectedProductCode || inputQuantitySold <= 0) {
      alert("Please check your selected values and quantities.");
      return;
    }

    // Verify stock availability
    const sourceProduct = rawDb.Products.find(p => p.ProductCode === selectedProductCode);
    if (!sourceProduct || Number(sourceProduct.CurrentStock) < Number(inputQuantitySold)) {
      alert(`Insufficient warehouse stock! Available: ${sourceProduct?.CurrentStock || 0} units.`);
      return;
    }

    try {
      // 1. Post new sales log transaction entry
      await axios.post("http://localhost:5000/api/data/SalesOrder", {
        BatchNumber: selectedBatchNumber,
        QuantitySold: inputQuantitySold,
        TotalCostAmount: autoCalculatedPrice,
        SalesDate: new Date().toISOString().split('T')[0]
      });

      // 2. Automate stock deduction optimization override
      const updatedStockVolume = Number(sourceProduct.CurrentStock) - Number(inputQuantitySold);
      await axios.post(`http://localhost:5000/api/data/Products`, {
        ...sourceProduct,
        CurrentStock: updatedStockVolume
      });

      // Reset transaction form states and refresh view logs
      setSelectedProductCode("");
      setSelectedBatchNumber("");
      setInputQuantitySold(1);
      await fetchStockReportData();
      alert("Sales order posted successfully. Warehouse inventory volumes updated.");
    } catch (err) {
      console.error("Failed to commit automated business sales action transaction:", err);
    }
  };

  return (
    <div className="mx-auto max-w-7xl p-4 sm:p-6 lg:p-8 bg-slate-50/50 min-h-screen space-y-8 print:bg-white print:p-0 print:m-0">
      
      {/* Action Banner Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-slate-200 pb-5 print:hidden">
        <div>
          <span className="text-[10px] font-bold uppercase tracking-wider text-indigo-600 bg-indigo-50 px-2.5 py-1 rounded-full">
            Inventory Turnover Audit Panel
          </span>
          <h2 className="text-2xl font-black tracking-tight text-slate-950 mt-2">Enterprise Commercial Sales Reports</h2>
          <p className="text-xs text-slate-400 mt-0.5">Rubavu Distribution Hub — Real-time Stock Reconciliation.</p>
        </div>
      </div>

      {/* NEW INTERACTIVE ORDER FORM — HIDDEN ON PRINT */}
     

      {/* Analytics Controllers Panel */}
      <div className="grid gap-4 rounded-2xl border border-slate-100 bg-white p-5 shadow-sm sm:grid-cols-3 print:hidden">
        <div className="space-y-1.5">
          <label className="block text-xs font-bold tracking-wide text-slate-500 uppercase">Filter Scope</label>
          <select
            value={filterType}
            onChange={(e) => {
              setFilterType(e.target.value);
              if (e.target.value === "all") setTargetDate("");
            }}
            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:outline-none focus:border-indigo-500 font-medium"
          >
            <option value="all">Show All Historical Sales Logs</option>
            <option value="daily">Daily Turnover Summary</option>
            <option value="weekly">Weekly Trailing Window</option>
            <option value="monthly">Monthly Calendar Bounds</option>
          </select>
        </div>

        <div className={`space-y-1.5 ${filterType === "all" ? "opacity-40 pointer-events-none" : ""}`}>
          <label className="block text-xs font-bold tracking-wide text-slate-500 uppercase">Select Target Date</label>
          <input
            type="date"
            value={targetDate}
            onChange={(e) => setTargetDate(e.target.value)}
            disabled={filterType === "all"}
            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:outline-none focus:border-indigo-500 font-medium disabled:bg-slate-100"
          />
        </div>

        <div className="grid grid-cols-2 gap-3 bg-slate-900 p-4 rounded-xl shadow-inner text-white">
          <div className="flex flex-col justify-center">
            <span className="text-[9px] font-bold uppercase text-slate-400 tracking-wider">Gross Turnover</span>
            <span className="text-sm font-black text-emerald-400 font-mono mt-0.5">{totalRevenueGenerated.toLocaleString()} Rwf</span>
          </div>
          <div className="flex flex-col justify-center border-l border-slate-800 pl-4">
            <span className="text-[9px] font-bold uppercase text-slate-400 tracking-wider">Dispatched Volume</span>
            <span className="text-sm font-black text-indigo-400 font-mono mt-0.5">{totalUnitsDispatched.toLocaleString()} Units</span>
          </div>
        </div>
      </div>

      {/* Main Container Layout */}
      <div className="grid gap-8 lg:grid-cols-3 items-start print:block print:w-full">
        
        {/* Left Side Table Queue */}
        <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden lg:col-span-2 print: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">Consolidated Sales Dispatch Stream</h3>
              <p className="text-slate-400 text-[11px] mt-0.5">Real-time ledger audit log registry.</p>
            </div>
            <span className="text-xs bg-slate-800 text-slate-300 font-mono font-bold px-2 py-1 rounded-md">
              Matching Records: {filteredLogs.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">Product Details</th>
                  <th className="p-4">Batch Lineage</th>
                  <th className="p-4 text-center">Qty Sold</th>
                  <th className="p-4 text-right">Total Net Cost</th>
                  <th className="p-4 text-center">Receipt</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filteredLogs.length === 0 ? (
                  <tr>
                    <td colSpan="5" className="p-12 text-center text-slate-400 font-medium">
                      No matching sales data tracks match specified conditions.
                    </td>
                  </tr>
                ) : (
                  filteredLogs.map((item) => (
                    <tr key={item.InvoiceNumber} className="hover:bg-slate-50/50 transition-colors font-medium text-slate-700">
                      <td className="p-4 text-slate-900 font-black bg-slate-50/30">
                        <span className="font-bold text-slate-900 block tracking-tight">{item.ProductName}</span>
                        <span className="text-xs text-slate-400 font-medium font-mono">{item.ProductCode} ({item.Category})</span>
                      </td>
                      <td className="p-4 text-slate-700">
                        <span className="font-semibold block text-slate-900">Batch #{item.BatchNumber}</span>
                        <span className="text-[11px] font-mono text-slate-400 block">
                          Sold: {item.SalesDate ? new Date(item.SalesDate).toLocaleDateString("en-GB") : "N/A"}
                        </span>
                      </td>
                      <td className="p-4 text-center font-bold font-mono text-slate-900">{item.QuantitySold}</td>
                      <td className="p-4 text-right font-black font-mono text-slate-950 whitespace-nowrap">
                        {item.TotalCostAmount.toLocaleString()} Rwf
                      </td>
                      <td className="p-4 text-center">
                        <button
                          onClick={() => setSelectedInvoice(item)}
                          className="rounded-xl bg-indigo-50 hover:bg-indigo-600 text-indigo-700 hover:text-white px-3 py-1.5 text-xs font-bold transition-all shadow-sm"
                        >
                          Invoice
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Right Side Billing Container */}
        <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-6 lg:col-span-1 print:border-none print:shadow-none print:p-0 print:w-full print:max-w-md print:mx-auto print:block">
          {selectedInvoice ? (
            <div className="space-y-6">
              
              <div className="border-b border-dashed border-slate-200 pb-5 text-center">
                <span className="text-[10px] font-bold uppercase tracking-widest text-indigo-600 bg-indigo-50 px-2.5 py-1 rounded-full print:bg-transparent">
                  SMS Enterprise Inventory Statement
                </span>
                <h3 className="text-xl font-black text-slate-900 tracking-tight mt-3">Commercial Sales Dispatch</h3>
                <div className="text-[10px] text-slate-400 font-mono mt-1">Invoice ID: #INV000{selectedInvoice.InvoiceNumber}</div>
              </div>

              <div className="space-y-3 text-xs font-medium text-slate-700">
                <div className="flex justify-between"><span className="text-slate-400 font-bold uppercase text-[10px]">Product Code</span><span className="font-black text-slate-900 font-mono">{selectedInvoice.ProductCode}</span></div>
                <div className="flex justify-between"><span className="text-slate-400">Item Name</span><span className="text-slate-900 font-bold">{selectedInvoice.ProductName}</span></div>
                <div className="flex justify-between"><span className="text-slate-400">Category Group</span><span className="text-slate-800 font-semibold">{selectedInvoice.Category}</span></div>
                <div className="flex justify-between"><span className="text-slate-400">Assigned Inbound Source</span><span className="font-bold text-indigo-600">Batch #{selectedInvoice.BatchNumber}</span></div>
                <hr className="border-slate-100 my-2" />
                <div className="flex justify-between"><span className="text-slate-400">Supplier Vendor</span><span className="font-semibold text-slate-900">{selectedInvoice.SupplierName}</span></div>
                <div className="flex justify-between"><span className="text-slate-400">Transaction Date</span><span className="font-mono text-slate-800">{selectedInvoice.SalesDate ? new Date(selectedInvoice.SalesDate).toLocaleDateString("en-GB") : "N/A"}</span></div>
              </div>

              <div className="rounded-xl bg-slate-50 p-4 border border-slate-100 space-y-2 print:bg-white print:border-slate-200">
                <div className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Pricing Breakdown Matrix</div>
                <div className="flex justify-between items-baseline text-xs">
                  <span className="text-slate-600">{selectedInvoice.QuantitySold} Unit(s) x {selectedInvoice.UnitPrice.toLocaleString()} Rwf</span>
                  <span className="font-mono font-black text-slate-900">{selectedInvoice.TotalCostAmount.toLocaleString()} Rwf</span>
                </div>
              </div>

              <div className="space-y-2 border-t border-slate-100 pt-4 print:border-slate-200">
                <div className="flex justify-between items-baseline pt-1 text-sm">
                  <span className="font-black text-slate-900">Total Valuation Charge:</span>
                  <span className="font-mono font-black text-base text-indigo-600">
                    {selectedInvoice.TotalCostAmount.toLocaleString()} Rwf
                  </span>
                </div>
              </div>

              <div className="bg-slate-900 text-slate-300 p-4 rounded-xl text-center space-y-1 print:bg-slate-50 print:text-slate-800 print:border print:border-slate-200">
                <div className="text-[10px] text-slate-400 uppercase tracking-widest font-bold">Issuing Logistic Outbound Agent</div>
                <div className="text-sm font-black text-white tracking-wide print:text-slate-950">SMS STOCKS WAREHOUSE</div>
                <div className="text-[10px] text-slate-500 font-medium italic">Rubavu Station Counter — Republic of Rwanda</div>
              </div>

              <button 
                onClick={() => window.print()}
                className="w-full rounded-xl bg-indigo-600 text-white font-bold py-3 text-center text-sm shadow-md hover:bg-indigo-700 transition-colors print:hidden"
              >
                Print Cargo Invoice Receipt
              </button>
            </div>
          ) : (
            <div className="py-24 text-center space-y-3 border border-dashed border-slate-200 rounded-2xl bg-slate-50/50 print:hidden">
              <div className="bg-slate-100 text-slate-400 rounded-full p-3 w-fit mx-auto">
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>
              </div>
              <p className="text-xs font-bold text-slate-400 max-w-[200px] mx-auto leading-relaxed">
                Click the "Invoice" button inside any dispatch row item to construct its official print receipt view.
              </p>
            </div>
          )}
        </div>

      </div>

    </div>
  );
}