import { useEffect, useState } from 'react';
import axios from 'axios';
import AppLayout from '../components/AppLayout';

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

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

  const fetchReports = async () => {
    try {
      const res = await axios.get('http://localhost:1000/api/reports/summary', { headers });
      setReports(res.data);
    } catch (err) {
      setError('Could not load reports');
      console.log(err);
    }
  };

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

  return (
    <AppLayout title="Stock reports" subtitle="Summary">
      <div className="mx-auto max-w-3xl">
        {error && <p className="alert-error mb-4">{error}</p>}

        {!reports ? (
          <p className="text-sm text-slate-500">Loading report summary...</p>
        ) : (
          <div className="space-y-6">
            <div className="grid gap-3 sm:grid-cols-3">
              {['day', 'week', 'month'].map((period) => (
                <div key={period} className="card p-4">
                  <h2 className="text-sm font-semibold capitalize text-brand-900">{period}</h2>
                  <dl className="mt-2 space-y-1 text-xs text-slate-600">
                    <div className="flex justify-between">
                      <dt>Stock in</dt>
                      <dd className="font-medium text-slate-800">{reports.totals[period].stockIn}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt>Stock out</dt>
                      <dd className="font-medium text-slate-800">{reports.totals[period].stockOut}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt>Transactions</dt>
                      <dd className="font-medium text-slate-800">{reports.totals[period].transactions}</dd>
                    </div>
                  </dl>
                </div>
              ))}
            </div>

            <div className="card p-5">
              <h2 className="text-sm font-semibold text-brand-900">Available stock</h2>
              <div className="mt-3 space-y-2">
                {reports.availableStock.length === 0 ? (
                  <p className="text-sm text-slate-500">No product stock available.</p>
                ) : (
                  reports.availableStock.map((product) => (
                    <div
                      key={product.productCode}
                      className="rounded-md border border-slate-100 bg-surface px-3 py-2 text-sm"
                    >
                      <p className="font-medium text-slate-800">
                        {product.productName}{' '}
                        <span className="text-slate-400">({product.productCode})</span>
                      </p>
                      <p className="mt-1 text-xs text-slate-500">
                        {product.category} · Qty {product.quantityInStock} · {product.supplierName}
                      </p>
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}

export default Reports;
