import React, { useState, useEffect } from 'react';
import axios from 'axios'; // FIXED: Corrected import target from 'react' to 'axios'

function Report() {
  const [dailySales, setDailySales] = useState([]);
  const [stockStatus, setStockStatus] = useState([]);

  // Search Filter state keys
  const [salesSearch, setSalesSearch] = useState('');
  const [stockSearch, setStockSearch] = useState('');

  useEffect(() => {
    // Fetch live structural updates from backend routers
    axios.get('http://localhost:5000/api/sales/daily-report').then(res => setDailySales(res.data));
    axios.get('http://localhost:5000/api/stock').then(res => setStockStatus(res.data));
  }, []);

  // --- DOWNLOAD FUNCTION ENGINES (PURE SCALAR CSV PARSING BLOB GENERATOR) ---
  const downloadCSV = (headers, dataRows, filename) => {
    // Convert arrays into structural comma separated raw CSV content lines
    const csvContent = [
      headers.join(','),
      ...dataRows.map(row => row.map(val => `"${String(val).replace(/"/g, '""')}"`).join(','))
    ].join('\n');

    // Generate blob format payload and simulate instant link anchor download process
    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', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleDownloadSales = () => {
    const headers = ['Product Name', 'Quantity Sold', 'Unit Price (RWF)', 'Total Earned (RWF)'];
    const rows = filteredSales.map(s => [
      s.product_name,
      s.sold_quantity,
      s.sold_unit_price,
      s.sold_total_price
    ]);
    downloadCSV(headers, rows, `Daily_Sales_Report_${new Date().toISOString().split('T')[0]}.csv`);
  };

  const handleDownloadStock = () => {
    const headers = ['Product Name', 'Stored Quantity', 'Sold Quantity', 'Remaining Quantity'];
    const rows = filteredStock.map(stock => [
      stock.product_name,
      stock.stored_quantity || 0,
      stock.sold_quantity || 0,
      (parseInt(stock.stored_quantity, 10) || 0) - (parseInt(stock.sold_quantity, 10) || 0)
    ]);
    downloadCSV(headers, rows, `Daily_Stock_Status_Report_${new Date().toISOString().split('T')[0]}.csv`);
  };

  // --- FILTER ARRAYS COMPUTATION LAYERS ---
  const filteredSales = dailySales.filter(s =>
    (s.product_name || '').toLowerCase().includes(salesSearch.toLowerCase())
  );

  const filteredStock = stockStatus.filter(stock =>
    (stock.product_name || '').toLowerCase().includes(stockSearch.toLowerCase())
  );

  return (
    <div className="space-y-10 max-w-5xl mx-auto px-4 py-2">
      
      {/* Item 11: Daily Sales Report Log */}
      <div className="bg-white p-6 rounded-xl shadow-md border border-gray-100">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between border-b pb-3 mb-4 gap-3">
          <h2 className="text-xl font-bold text-indigo-900 flex items-center gap-1.5">
            📊 Item 11: Daily Sales Transaction Report
          </h2>
          <div className="flex items-center gap-2">
            <input 
              type="text"
              placeholder="Search sales item..."
              value={salesSearch}
              onChange={e => setSalesSearch(e.target.value)}
              className="p-2 border border-slate-200 text-xs rounded-xl outline-none focus:border-indigo-500 w-48 font-medium"
            />
            <button 
              onClick={handleDownloadSales}
              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"
            >
              📥 Download CSV
            </button>
          </div>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-100 text-slate-700 text-sm uppercase font-semibold">
                <th className="p-3 border">Product Name</th>
                <th className="p-3 border">Quantity Sold</th>
                <th className="p-3 border">Unit Price</th>
                <th className="p-3 border">Total Earned Metrics</th>
              </tr>
            </thead>
            <tbody className="text-gray-700">
              {filteredSales.length === 0 ? (
                <tr>
                  <td colSpan="4" className="text-center p-6 text-gray-400 italic">
                    No matching sales records located in database context.
                  </td>
                </tr>
              ) : filteredSales.map(s => (
                <tr key={s.product_id || s.sales_id} className="hover:bg-slate-50 transition-colors">
                  <td className="p-3 border font-medium">{s.product_name}</td>
                  <td className="p-3 border font-mono">{s.sold_quantity}</td>
                  <td className="p-3 border font-mono">{parseFloat(s.sold_unit_price || 0).toLocaleString()} RWF</td>
                  <td className="p-3 border font-mono text-emerald-600 font-bold">
                    {parseFloat(s.sold_total_price || 0).toLocaleString()} RWF
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Item 12: Daily Stock Status Report */}
      <div className="bg-white p-6 rounded-xl shadow-md border border-gray-100">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between border-b pb-3 mb-4 gap-3">
          <h2 className="text-xl font-bold text-indigo-900 flex items-center gap-1.5">
            📈 Item 12: Daily Stock Status Inventory Balance Report
          </h2>
          <div className="flex items-center gap-2">
            <input 
              type="text"
              placeholder="Search warehouse items..."
              value={stockSearch}
              onChange={e => setStockSearch(e.target.value)}
              className="p-2 border border-slate-200 text-xs rounded-xl outline-none focus:border-indigo-500 w-48 font-medium"
            />
            <button 
              onClick={handleDownloadStock}
              className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs px-3 py-2 rounded-xl flex items-center gap-1 shadow-sm transition-all"
            >
              📥 Download CSV
            </button>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-100 text-slate-700 text-sm uppercase font-semibold">
                <th className="p-3 border">Product Name</th>
                <th className="p-3 border">Stored Quantity</th>
                <th className="p-3 border">Sold Quantity</th>
                <th className="p-3 border">Remaining Quantity</th>
              </tr>
            </thead>
            <tbody className="text-gray-700">
              {filteredStock.length === 0 ? (
                <tr>
                  <td colSpan="4" className="text-center p-6 text-gray-400 italic">
                    No warehouse status parameters configurations mapped yet.
                  </td>
                </tr>
              ) : filteredStock.map(stock => {
                const remaining = (parseInt(stock.stored_quantity, 10) || 0) - (parseInt(stock.sold_quantity, 10) || 0);
                return (
                  <tr key={stock.product_id} className="hover:bg-slate-50 transition-colors">
                    <td className="p-3 border font-semibold text-slate-800">{stock.product_name}</td>
                    <td className="p-3 border font-mono text-blue-600 font-medium">{stock.stored_quantity || 0}</td>
                    <td className="p-3 border font-mono text-amber-600 font-medium">{stock.sold_quantity || 0}</td>
                    <td className={`p-3 border font-mono font-extrabold ${remaining <= 3 ? 'text-rose-600 bg-rose-50/40' : 'text-emerald-600 bg-emerald-50/40'}`}>
                      {remaining} Available
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

    </div>
  );
}

export default Report;