import { useState } from 'react';
import { getStockReport } from '../services/apiService';
import { getDateRange, formatCurrency } from '../utils/helpers';

const ReportsPage = () => {
  const [reportType, setReportType] = useState('daily');
  const [reportData, setReportData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleGenerateReport = async (type) => {
    setReportType(type);
    setLoading(true);
    setError('');

    try {
      const dateRange = getDateRange(type);
      const response = await getStockReport(dateRange.startDate, dateRange.endDate, type);
      setReportData(response.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Error generating report');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6">
      <h2 className="text-2xl sm:text-3xl font-bold mb-6 text-gray-800">Inventory Reports</h2>

      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 className="text-xl font-bold mb-4 text-gray-800">Select Report Period</h3>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {['daily', 'weekly', 'monthly'].map((type) => (
            <button key={type} onClick={() => handleGenerateReport(type)}
              className={`p-4 rounded-lg font-bold transition capitalize ${
                reportType === type ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
              }`}>
              {type} Report
            </button>
          ))}
        </div>
      </div>

      {loading && (
        <div className="bg-white rounded-lg shadow-md p-6 text-center">
          <p className="text-gray-600">Generating report...</p>
        </div>
      )}

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">{error}</div>
      )}

      {reportData && !loading && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-blue-100 rounded-lg shadow-md p-5">
              <h4 className="text-gray-700 font-bold mb-1">Available Stock</h4>
              <p className="text-3xl font-bold text-blue-600">{reportData.summary.totalAvailableStock}</p>
              <p className="text-xs text-gray-600 mt-1">Total units in inventory</p>
            </div>
            <div className="bg-green-100 rounded-lg shadow-md p-5">
              <h4 className="text-gray-700 font-bold mb-1">Stock In</h4>
              <p className="text-3xl font-bold text-green-600">{reportData.summary.totalStockIn}</p>
              <p className="text-xs text-gray-600 mt-1">Units received in period</p>
            </div>
            <div className="bg-red-100 rounded-lg shadow-md p-5">
              <h4 className="text-gray-700 font-bold mb-1">Stock Out</h4>
              <p className="text-3xl font-bold text-red-600">{reportData.summary.totalStockOut}</p>
              <p className="text-xs text-gray-600 mt-1">Units dispatched in period</p>
            </div>
            <div className="bg-purple-100 rounded-lg shadow-md p-5">
              <h4 className="text-gray-700 font-bold mb-1">Transactions</h4>
              <p className="text-3xl font-bold text-purple-600">{reportData.summary.transactionCount}</p>
              <p className="text-xs text-gray-600 mt-1">In selected period</p>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-xl font-bold mb-4 text-gray-800 capitalize">
              {reportData.reportType} Report — Available Stock
            </h3>
            {reportData.availableStock.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full border-collapse text-sm">
                  <thead>
                    <tr className="bg-gray-200">
                      <th className="border px-3 py-2 text-left">Code</th>
                      <th className="border px-3 py-2 text-left">Name</th>
                      <th className="border px-3 py-2 text-left">Category</th>
                      <th className="border px-3 py-2 text-right">Qty In Stock</th>
                      <th className="border px-3 py-2 text-right">Unit Price</th>
                      <th className="border px-3 py-2 text-left">Supplier</th>
                    </tr>
                  </thead>
                  <tbody>
                    {reportData.availableStock.map((p) => (
                      <tr key={p._id} className="hover:bg-gray-100">
                        <td className="border px-3 py-2">{p.productCode}</td>
                        <td className="border px-3 py-2">{p.productName}</td>
                        <td className="border px-3 py-2">{p.category}</td>
                        <td className="border px-3 py-2 text-right font-bold">{p.quantityInStock}</td>
                        <td className="border px-3 py-2 text-right">{formatCurrency(p.unitPrice)}</td>
                        <td className="border px-3 py-2">{p.supplierName}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-600">No products in inventory.</p>
            )}
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-lg font-bold mb-4 text-green-700">Stock In Transactions</h3>
              {reportData.stockInTransactions.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-sm">
                    <thead>
                      <tr className="bg-green-50">
                        <th className="border px-2 py-2 text-left">Date</th>
                        <th className="border px-2 py-2 text-left">Product</th>
                        <th className="border px-2 py-2 text-right">Qty</th>
                      </tr>
                    </thead>
                    <tbody>
                      {reportData.stockInTransactions.map((t) => (
                        <tr key={t._id}>
                          <td className="border px-2 py-2">{new Date(t.transactionDate).toLocaleDateString()}</td>
                          <td className="border px-2 py-2">{t.productId?.productName}</td>
                          <td className="border px-2 py-2 text-right">{t.quantityMoved}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="text-gray-600">No stock in transactions in this period.</p>
              )}
            </div>

            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-lg font-bold mb-4 text-red-700">Stock Out Transactions</h3>
              {reportData.stockOutTransactions.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-sm">
                    <thead>
                      <tr className="bg-red-50">
                        <th className="border px-2 py-2 text-left">Date</th>
                        <th className="border px-2 py-2 text-left">Product</th>
                        <th className="border px-2 py-2 text-right">Qty</th>
                      </tr>
                    </thead>
                    <tbody>
                      {reportData.stockOutTransactions.map((t) => (
                        <tr key={t._id}>
                          <td className="border px-2 py-2">{new Date(t.transactionDate).toLocaleDateString()}</td>
                          <td className="border px-2 py-2">{t.productId?.productName}</td>
                          <td className="border px-2 py-2 text-right">{t.quantityMoved}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="text-gray-600">No stock out transactions in this period.</p>
              )}
            </div>
          </div>
        </div>
      )}

      {!reportData && !loading && !error && (
        <div className="bg-white rounded-lg shadow-md p-6 text-center">
          <p className="text-gray-600">Select a report period to view inventory data</p>
        </div>
      )}
    </div>
  );
};

export default ReportsPage;
