import React, { useEffect, useMemo, useState } from "react";
import { getDeliveries } from "../api/deliveryApi";
import { getShipments } from "../api/shipmentApi";
import { getSuppliers } from "../api/supplierApi";
import PageHeader from "../components/PageHeader";

function formatDate(dateValue) {
  if (!dateValue) return "";
  return new Date(dateValue).toISOString().split("T")[0];
}

function getPeriodRange(period) {
  var now = new Date();
  var start = new Date(now);
  var end = new Date(now);

  start.setHours(0, 0, 0, 0);
  end.setHours(23, 59, 59, 999);

  if (period === "weekly") {
    start.setDate(now.getDate() - now.getDay());
  }

  if (period === "monthly") {
    start.setDate(1);
  }

  return { start: start, end: end };
}

function isInPeriod(dateValue, period) {
  if (!dateValue) return false;
  var date = new Date(dateValue);
  var range = getPeriodRange(period);
  return date >= range.start && date <= range.end;
}

function Reports() {
  var periodState = useState("daily");
  var period = periodState[0];
  var setPeriod = periodState[1];
  var reportTypeState = useState("suppliers");
  var reportType = reportTypeState[0];
  var setReportType = reportTypeState[1];
  var supplierState = useState([]);
  var suppliers = supplierState[0];
  var setSuppliers = supplierState[1];
  var shipmentState = useState([]);
  var shipments = shipmentState[0];
  var setShipments = shipmentState[1];
  var deliveryState = useState([]);
  var deliveries = deliveryState[0];
  var setDeliveries = deliveryState[1];

  useEffect(function () {
    function loadReports() {
      Promise.all([
        getSuppliers(),
        getShipments(),
        getDeliveries(),
      ])
        .then(function (responses) {
          setSuppliers(responses[0].data);
          setShipments(responses[1].data);
          setDeliveries(responses[2].data);
        });
    }

    loadReports();
  }, []);

  var reportRows = useMemo(function () {
    if (reportType === "suppliers") {
      return suppliers.filter(function (supplier) {
        return isInPeriod(supplier.createdAt, period);
      });
    }

    if (reportType === "shipments") {
      return shipments.filter(function (shipment) {
        return isInPeriod(shipment.shipmentDate, period);
      });
    }

    return deliveries.filter(function (delivery) {
      return isInPeriod(delivery.deliveryDate, period);
    });
  }, [period, reportType, suppliers, shipments, deliveries]);

  return (
    <div className="print-area">
      <div className="no-print">
        <PageHeader title="Reports" subtitle="Daily, weekly, and monthly printable reports" />

        <div className="mb-5 grid gap-3 rounded-md border border-slate-200 bg-white p-4 md:grid-cols-3">
          <div>
            <label className="mb-2 block text-sm font-semibold">Period</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" value={period} onChange={function (event) { setPeriod(event.target.value); }}>
              <option value="daily">Daily Report</option>
              <option value="weekly">Weekly Report</option>
              <option value="monthly">Monthly Report</option>
            </select>
          </div>

          <div>
            <label className="mb-2 block text-sm font-semibold">Records</label>
            <select className="w-full rounded-md border border-slate-200 bg-slate-50 px-3 py-2 outline-blue-900" value={reportType} onChange={function (event) { setReportType(event.target.value); }}>
              <option value="suppliers">Suppliers</option>
              <option value="shipments">Shipments</option>
              <option value="deliveries">Deliveries</option>
            </select>
          </div>

          <div className="flex items-end">
            <button onClick={function () { window.print(); }} className="w-full rounded-md bg-blue-900 px-5 py-2 font-semibold text-slate-50">
              Print Report
            </button>
          </div>
        </div>
      </div>

      <section className="rounded-md border border-slate-200 bg-white p-4">
        <div className="mb-4 text-center">
          <h2 className="text-xl font-bold">SupplyNet Ltd</h2>
          <p className="text-sm text-blue-800">Supply Chain Management System</p>
          <p className="mt-2 text-sm font-semibold capitalize">
            {period} {reportType} report
          </p>
          <p className="text-sm text-blue-800">Generated on {formatDate(new Date())}</p>
        </div>

        <div className="overflow-x-auto">
          {reportType === "suppliers" && (
            <table className="w-full min-w-[760px] text-left text-sm">
              <thead className="bg-blue-900 text-slate-50">
                <tr>
                  <th className="p-3">Code</th>
                  <th className="p-3">Name</th>
                  <th className="p-3">Telephone</th>
                  <th className="p-3">Address</th>
                  <th className="p-3">Email</th>
                </tr>
              </thead>
              <tbody>
                {reportRows.map(function (supplier) {
                  return (
                  <tr key={supplier._id} className="border-t border-slate-200">
                    <td className="p-3">{supplier.supplierCode}</td>
                    <td className="p-3">{supplier.supplierName}</td>
                    <td className="p-3">{supplier.telephone}</td>
                    <td className="p-3">{supplier.address}</td>
                    <td className="p-3">{supplier.email}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          )}

          {reportType === "shipments" && (
            <table className="w-full min-w-[820px] text-left text-sm">
              <thead className="bg-blue-900 text-slate-50">
                <tr>
                  <th className="p-3">Shipment No</th>
                  <th className="p-3">Date</th>
                  <th className="p-3">Supplier</th>
                  <th className="p-3">Destination</th>
                  <th className="p-3">Status</th>
                </tr>
              </thead>
              <tbody>
                {reportRows.map(function (shipment) {
                  return (
                  <tr key={shipment._id} className="border-t border-slate-200">
                    <td className="p-3">{shipment.shipmentNumber}</td>
                    <td className="p-3">{formatDate(shipment.shipmentDate)}</td>
                    <td className="p-3">{shipment.supplier ? shipment.supplier.supplierName : ""}</td>
                    <td className="p-3">{shipment.destination}</td>
                    <td className="p-3">{shipment.shipmentStatus}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          )}

          {reportType === "deliveries" && (
            <table className="w-full min-w-[820px] text-left text-sm">
              <thead className="bg-blue-900 text-slate-50">
                <tr>
                  <th className="p-3">Delivery Code</th>
                  <th className="p-3">Date</th>
                  <th className="p-3">Shipment</th>
                  <th className="p-3">Quantity</th>
                  <th className="p-3">Status</th>
                </tr>
              </thead>
              <tbody>
                {reportRows.map(function (delivery) {
                  return (
                  <tr key={delivery._id} className="border-t border-slate-200">
                    <td className="p-3">{delivery.deliveryCode}</td>
                    <td className="p-3">{formatDate(delivery.deliveryDate)}</td>
                    <td className="p-3">{delivery.shipment ? delivery.shipment.shipmentNumber : ""}</td>
                    <td className="p-3">{delivery.quantityDelivered}</td>
                    <td className="p-3">{delivery.deliveryStatus}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {reportRows.length === 0 && <p className="mt-4 text-center text-sm font-semibold">No records found for this report.</p>}
      </section>
    </div>
  );
}

export default Reports;
