import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

function Reports() {
  const [report, setReport] = useState(null);
  const [error, setError] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const loadReport = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/reports', { headers });
      setReport(res.data);
    } catch (err) {
      setError('Failed to load reports');
      console.log(err);
    }
  };

  useEffect(() => {
    loadReport();
  }, []);

  return (
    <div className="max-w-3xl mx-auto p-4">
      <div className="mt-3 mb-6">
        <Link
          to="/dashboard"
          type="button"
          className="font-medium hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
        >
          BACK
        </Link>
      </div>

      <h1 className="text-2xl font-bold mb-4">Inventory Reports</h1>

      {error && <p className="mb-4 text-red-600">{error}</p>}

      {!report ? (
        <p className="text-slate-600">Loading report...</p>
      ) : (
        <>
          <div className="grid gap-4 sm:grid-cols-3 mb-6">
            <div className="border rounded-lg p-4 bg-white">
              <p className="text-sm text-slate-500">Total Spare Parts</p>
              <p className="text-2xl font-semibold mt-2">{report.totalSpareParts}</p>
            </div>
            <div className="border rounded-lg p-4 bg-white">
              <p className="text-sm text-slate-500">Total Stock Value</p>
              <p className="text-2xl font-semibold mt-2">${report.totalStockValue.toFixed(2)}</p>
            </div>
            <div className="border rounded-lg p-4 bg-white">
              <p className="text-sm text-slate-500">Low Stock Items</p>
              <p className="text-2xl font-semibold mt-2">{report.lowStockParts.length}</p>
            </div>
          </div>

          <div className="border rounded-lg p-4 bg-white">
            <h2 className="text-xl font-semibold mb-3">Low Stock Parts</h2>
            {report.lowStockParts.length === 0 ? (
              <p className="text-slate-600">No low stock parts found.</p>
            ) : (
              report.lowStockParts.map((part) => (
                <div key={part.id} className="border-b border-slate-200 py-3 last:border-b-0">
                  <p className="font-medium">{part.partCode} — {part.partName}</p>
                  <p className="text-sm text-slate-600">Quantity: {part.quantity} / Reorder Level: {part.reorderLevel}</p>
                  <p className="text-sm text-slate-500">Supplier: {part.supplier}</p>
                </div>
              ))
            )}
          </div>
        </>
      )}
    </div>
  );
}

export default Reports;
