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

function Dashboard(props) {
  var statsState = useState({ customers: 0, products: 0, sales: 0, revenue: 0 });
  var stats = statsState[0];
  var setStats = statsState[1];
  var loadingState = useState(true);
  var loading = loadingState[0];
  var setLoading = loadingState[1];

  var sessionData = JSON.parse(localStorage.getItem('srmsSession') || '{}');
  var token = sessionData.token || '';
  var headers = { Authorization: 'Bearer ' + token };

  useEffect(function() {
    axios.get(props.API + '/customers', { headers: headers })
      .then(function(custRes) {
        return Promise.all([
          Promise.resolve(custRes),
          axios.get(props.API + '/products', { headers: headers }),
          axios.get(props.API + '/sales', { headers: headers })
        ]);
      })
      .then(function(results) {
        var sales = results[2].data;
        var totalRevenue = 0;
        for (var i = 0; i < sales.length; i++) {
          totalRevenue += sales[i].totalAmountPaid || 0;
        }
        setStats({
          customers: results[0].data.length,
          products: results[1].data.length,
          sales: sales.length,
          revenue: totalRevenue
        });
      })
      .catch(function(err) {
        console.error('Dashboard fetch error:', err);
      })
      .then(function() {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return React.createElement('main', { className: 'page' },
      React.createElement('p', null, 'Loading dashboard...')
    );
  }

  return (
    <main className="page">
      <div className="page-title">
        <h2>Dashboard</h2>
        <p>Overview of the Sales Record Management System.</p>
      </div>
      <section className="cards-grid">
        <article className="card"><span>Total Customers</span><strong>{stats.customers}</strong></article>
        <article className="card"><span>Total Products</span><strong>{stats.products}</strong></article>
        <article className="card"><span>Total Sales</span><strong>{stats.sales}</strong></article>
        <article className="card"><span>Total Revenue</span><strong>{stats.revenue.toLocaleString()} FRW</strong></article>
      </section>
      <div style={{ marginTop: 16 }}>
        <Link to="/customers"><button style={{ marginRight: 8 }}>Add Customer</button></Link>
        <Link to="/products"><button style={{ marginRight: 8 }}>Add Product</button></Link>
        <Link to="/sales"><button>New Sale</button></Link>
      </div>
    </main>
  );
}

export default Dashboard;
