import React, { useState, useEffect } from 'react';
import { getDailySalesReport, getDailyStockReport } from '../utils/api';

export default function Reports() {
  const [tab, setTab] = useState('sales');
  const [salesDate, setSalesDate] = useState(new Date().toISOString().split('T')[0]);
  const [salesReport, setSalesReport] = useState(null);
  const [stockReport, setStockReport] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchSalesReport = async () => {
    setLoading(true); setError('');
    try {
      const res = await getDailySalesReport(salesDate);
      setSalesReport(res.data);
    } catch (err) {
      setError('Failed to load sales report');
    } finally {
      setLoading(false);
    }
  };

  const fetchStockReport = async () => {
    setLoading(true); setError('');
    try {
      const res = await getDailyStockReport();
      setStockReport(res.data);
    } catch (err) {
      setError('Failed to load stock report');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (tab === 'sales') fetchSalesReport();
    else fetchStockReport();
  }, [tab]);

  const handlePrint = () => window.print();

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-slate-800">Reports</h1>
          <p className="text-slate-500 text-sm mt-0.5">Generate daily sales and stock status reports</p>
        </div>
        <button onClick={handlePrint}
          className="flex items-center gap-2 border border-slate-300 hover:bg-slate-50 text-slate-600 text-sm font-medium px-4 py-2 rounded-lg transition-colors print:hidden">
          🖨️ Print Report
        </button>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 mb-6 print:hidden">
        <button onClick={() => setTab('sales')}
          className={`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'sales' ? 'bg-blue-600 text-white' : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50'}`}>
          📈 Daily Sales Report
        </button>
        <button onClick={() => setTab('stock')}
          className={`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'stock' ? 'bg-blue-600 text-white' : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50'}`}>
          📦 Daily Stock Status Report
        </button>
      </div>

      {error && <div className="bg-red-50 border border-red-200 text-red-700 rounded-lg px-4 py-3 text-sm mb-4">{error}</div>}

      {/* Daily Sales Report */}
      {tab === 'sales' && (
        <div>
          <div className="flex items-center gap-3 mb-4 print:hidden">
            <input type="date" value={salesDate} onChange={e => setSalesDate(e.target.value)}
              className="border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            <button onClick={fetchSalesReport} disabled={loading}
              className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-4 py-2 rounded-lg disabled:opacity-60 transition-colors">
              {loading ? 'Loading...' : 'Generate Report'}
            </button>
          </div>

          {salesReport && (
            <div>
              {/* Report Header */}
              <div className="bg-white border border-slate-200 rounded-xl p-6 mb-4">
                <div className="text-center border-b border-slate-100 pb-4 mb-4">
                  <h2 className="text-lg font-bold text-slate-800">DAB Enterprise Ltd</h2>
                  <p className="text-slate-500 text-sm">Kigali, Rwanda</p>
                  <p className="font-semibold text-slate-700 mt-2">Daily Sales Report</p>
                  <p className="text-slate-500 text-sm">Date: {new Date(salesReport.date).toLocaleDateString('en-RW', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
                </div>

                {/* Summary cards */}
                <div className="grid grid-cols-3 gap-4 mb-6">
                  <div className="bg-blue-50 rounded-lg p-4 text-center">
                    <p className="text-2xl font-bold text-blue-700">{salesReport.summary.totalTransactions}</p>
                    <p className="text-xs text-blue-600 mt-0.5">Transactions</p>
                  </div>
                  <div className="bg-green-50 rounded-lg p-4 text-center">
                    <p className="text-2xl font-bold text-green-700">{salesReport.summary.totalItemsSold}</p>
                    <p className="text-xs text-green-600 mt-0.5">Items Sold</p>
                  </div>
                  <div className="bg-yellow-50 rounded-lg p-4 text-center">
                    <p className="text-lg font-bold text-yellow-700">RWF {salesReport.summary.totalRevenue.toLocaleString()}</p>
                    <p className="text-xs text-yellow-600 mt-0.5">Total Revenue</p>
                  </div>
                </div>

                {salesReport.sales.length === 0 ? (
                  <p className="text-center text-slate-400 text-sm py-8">No sales recorded on this date.</p>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm border border-slate-200 rounded-lg overflow-hidden">
                      <thead className="bg-slate-800 text-white">
                        <tr>
                          {['#', 'Product', 'Category', 'Qty Sold', 'Unit Price (RWF)', 'Total (RWF)', 'Time'].map(h => (
                            <th key={h} className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wide">{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {salesReport.sales.map((s, i) => (
                          <tr key={s._id} className={i % 2 === 0 ? 'bg-white' : 'bg-slate-50'}>
                            <td className="px-4 py-3 text-slate-400">{i + 1}</td>
                            <td className="px-4 py-3 font-medium text-slate-800">{s.productId?.productName || 'N/A'}</td>
                            <td className="px-4 py-3 text-slate-500">{s.productId?.category || 'N/A'}</td>
                            <td className="px-4 py-3 text-slate-700">{s.soldQuantity}</td>
                            <td className="px-4 py-3 text-slate-700">{s.soldUnitPrice?.toLocaleString()}</td>
                            <td className="px-4 py-3 font-semibold text-green-700">{s.soldTotalPrice?.toLocaleString()}</td>
                            <td className="px-4 py-3 text-slate-400 text-xs">{new Date(s.salesDate).toLocaleTimeString()}</td>
                          </tr>
                        ))}
                        <tr className="bg-slate-800 text-white">
                          <td colSpan="3" className="px-4 py-3 font-semibold text-right">TOTAL</td>
                          <td className="px-4 py-3 font-bold">{salesReport.summary.totalItemsSold}</td>
                          <td className="px-4 py-3"></td>
                          <td className="px-4 py-3 font-bold">{salesReport.summary.totalRevenue.toLocaleString()}</td>
                          <td></td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Daily Stock Status Report */}
      {tab === 'stock' && (
        <div>
          <div className="flex items-center gap-3 mb-4 print:hidden">
            <button onClick={fetchStockReport} disabled={loading}
              className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-4 py-2 rounded-lg disabled:opacity-60 transition-colors">
              {loading ? 'Loading...' : 'Refresh Report'}
            </button>
          </div>

          {stockReport && (
            <div className="bg-white border border-slate-200 rounded-xl p-6">
              <div className="text-center border-b border-slate-100 pb-4 mb-4">
                <h2 className="text-lg font-bold text-slate-800">DAB Enterprise Ltd</h2>
                <p className="text-slate-500 text-sm">Kigali, Rwanda</p>
                <p className="font-semibold text-slate-700 mt-2">Daily Stock Status Report</p>
                <p className="text-slate-500 text-sm">Generated: {new Date(stockReport.date).toLocaleString()}</p>
              </div>

              {/* Summary */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
                <div className="bg-blue-50 rounded-lg p-3 text-center">
                  <p className="text-xl font-bold text-blue-700">{stockReport.summary.totalProducts}</p>
                  <p className="text-xs text-blue-600 mt-0.5">Total Products</p>
                </div>
                <div className="bg-green-50 rounded-lg p-3 text-center">
                  <p className="text-xl font-bold text-green-700">{stockReport.summary.inStock}</p>
                  <p className="text-xs text-green-600 mt-0.5">In Stock</p>
                </div>
                <div className="bg-yellow-50 rounded-lg p-3 text-center">
                  <p className="text-xl font-bold text-yellow-700">{stockReport.summary.lowStock}</p>
                  <p className="text-xs text-yellow-600 mt-0.5">Low Stock</p>
                </div>
                <div className="bg-red-50 rounded-lg p-3 text-center">
                  <p className="text-xl font-bold text-red-700">{stockReport.summary.outOfStock}</p>
                  <p className="text-xs text-red-600 mt-0.5">Out of Stock</p>
                </div>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full text-sm border border-slate-200 rounded-lg overflow-hidden">
                  <thead className="bg-slate-800 text-white">
                    <tr>
                      {['#', 'Product Name', 'Category', 'Stored Quantity', 'Sold Quantity', 'Remaining Quantity', 'Status'].map(h => (
                        <th key={h} className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wide">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {stockReport.report.map((row, i) => (
                      <tr key={i} className={i % 2 === 0 ? 'bg-white' : 'bg-slate-50'}>
                        <td className="px-4 py-3 text-slate-400">{i + 1}</td>
                        <td className="px-4 py-3 font-medium text-slate-800">{row.productName}</td>
                        <td className="px-4 py-3 text-slate-500">{row.category}</td>
                        <td className="px-4 py-3 text-slate-700">{row.storedQuantity}</td>
                        <td className="px-4 py-3 text-slate-700">{row.soldQuantity}</td>
                        <td className="px-4 py-3 font-semibold text-slate-800">{row.remainingQuantity}</td>
                        <td className="px-4 py-3">
                          <span className={`text-xs px-2 py-1 rounded-full font-medium ${
                            row.status === 'Out of Stock' ? 'bg-red-100 text-red-700' :
                            row.status === 'Low Stock' ? 'bg-yellow-100 text-yellow-700' :
                            'bg-green-100 text-green-700'
                          }`}>{row.status}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
