import React, { useEffect, useState } from "react";
import { getReports } from "../api/reportApi";
import Layout from "../components/Layout";

const ReportsPage = ({ user, setUser }) => {
  const [period, setPeriod] = useState("daily");
  const [report, setReport] = useState({
    availableStock: [],
    stockIn: [],
    stockOut: []
  });

  const totalStockValue = report.availableStock.reduce(
    (total, product) => total + Number(product.quantityInStock || 0) * Number(product.unitPrice || 0),
    0
  );
  const totalStockIn = report.stockIn.reduce((total, item) => total + Number(item.quantityMoved || 0), 0);
  const totalStockOut = report.stockOut.reduce((total, item) => total + Number(item.quantityMoved || 0), 0);

  useEffect(() => {
    const loadReport = async () => {
      const data = await getReports(period);
      setReport(data);
    };

    loadReport();
  }, [period]);

  const renderTransactionRows = (transactions) => {
    if (!transactions.length) {
      return (
        <tr>
          <td colSpan="5" className="p-3 text-center">No records found</td>
        </tr>
      );
    }

    return transactions.map((transaction) => (
      <tr key={transaction._id} className="border-t border-primary">
        <td className="p-3">{transaction.transactionDate?.slice(0, 10)}</td>
        <td className="p-3">{transaction.product?.productName}</td>
        <td className="p-3">{transaction.warehouse?.warehouseName}</td>
        <td className="p-3">{transaction.quantityMoved}</td>
        <td className="p-3">{transaction.transactionType}</td>
      </tr>
    ));
  };

  return (
    <Layout title="Reports" user={user} setUser={setUser}>
      <div className="no-print mb-5 flex flex-col gap-3 rounded-md border border-primary p-4 sm:flex-row sm:items-center sm:justify-between">
        <select value={period} onChange={(event) => setPeriod(event.target.value)} className="rounded-md border border-primary bg-secondary p-3 outline-none">
          <option value="daily">Daily Report</option>
          <option value="weekly">Weekly Report</option>
          <option value="monthly">Monthly Report</option>
        </select>
        <button onClick={() => window.print()} className="rounded-md bg-primary px-5 py-3 font-semibold text-secondary">
          Print Report
        </button>
      </div>

      <section className="mb-6 grid gap-4 md:grid-cols-3">
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Available Stock Value</p>
          <p className="mt-2 text-2xl font-bold">{totalStockValue.toLocaleString()} FRW</p>
        </div>
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Stock In Quantity</p>
          <p className="mt-2 text-2xl font-bold">{totalStockIn}</p>
        </div>
        <div className="rounded-md border border-primary p-4">
          <p className="text-sm font-semibold">Stock Out Quantity</p>
          <p className="mt-2 text-2xl font-bold">{totalStockOut}</p>
        </div>
      </section>

      <section className="mb-6">
        <h3 className="mb-3 text-lg font-bold">Available Stock</h3>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[760px] border border-primary text-left text-sm">
            <thead className="bg-primary text-secondary">
              <tr>
                <th className="p-3">Code</th>
                <th className="p-3">Product</th>
                <th className="p-3">Category</th>
                <th className="p-3">Quantity</th>
                <th className="p-3">Unit Price</th>
                <th className="p-3">Stock Value</th>
              </tr>
            </thead>
            <tbody>
              {report.availableStock.length === 0 ? (
                <tr className="border-t border-primary">
                  <td colSpan="6" className="p-3 text-center">No products recorded</td>
                </tr>
              ) : (
                report.availableStock.map((product) => (
                  <tr key={product._id} className="border-t border-primary">
                    <td className="p-3">{product.productCode}</td>
                    <td className="p-3">{product.productName}</td>
                    <td className="p-3">{product.category}</td>
                    <td className="p-3">{product.quantityInStock}</td>
                    <td className="p-3">{product.unitPrice}</td>
                    <td className="p-3">{Number(product.quantityInStock) * Number(product.unitPrice)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>

      <section className="mb-6">
        <h3 className="mb-3 text-lg font-bold">Stock In</h3>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[760px] border border-primary text-left text-sm">
            <thead className="bg-primary text-secondary">
              <tr>
                <th className="p-3">Date</th>
                <th className="p-3">Product</th>
                <th className="p-3">Warehouse</th>
                <th className="p-3">Quantity</th>
                <th className="p-3">Type</th>
              </tr>
            </thead>
            <tbody>{renderTransactionRows(report.stockIn)}</tbody>
          </table>
        </div>
      </section>

      <section>
        <h3 className="mb-3 text-lg font-bold">Stock Out</h3>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[760px] border border-primary text-left text-sm">
            <thead className="bg-primary text-secondary">
              <tr>
                <th className="p-3">Date</th>
                <th className="p-3">Product</th>
                <th className="p-3">Warehouse</th>
                <th className="p-3">Quantity</th>
                <th className="p-3">Type</th>
              </tr>
            </thead>
            <tbody>{renderTransactionRows(report.stockOut)}</tbody>
          </table>
        </div>
      </section>
    </Layout>
  );
};

export default ReportsPage;
