import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { dashboardAPI } from '../services/api';
import './Dashboard.css';

const Dashboard = () => {
  const [summary, setSummary] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

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

  const fetchSummary = async () => {
    try {
      const { data } = await dashboardAPI.getSummary();
      setSummary(data);
    } catch {
      setError('Failed to load dashboard data.');
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

  const formatDate = (date) =>
    new Date(date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return 'Good morning';
    if (hour < 17) return 'Good afternoon';
    return 'Good evening';
  };

  if (loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner" />
        <span>Loading dashboard...</span>
      </div>
    );
  }

  if (error) return <div className="alert alert-error">{error}</div>;

  const stats = [
    { label: 'Total Products', value: summary.totalProducts, sub: 'In inventory', gradient: 'stat-blue', link: '/products' },
    { label: 'Total Customers', value: summary.totalCustomers, sub: 'Registered', gradient: 'stat-green', link: '/customers' },
    { label: 'Total Sales', value: summary.totalSales, sub: 'Transactions', gradient: 'stat-amber', link: '/sales' },
    { label: 'Total Revenue', value: formatCurrency(summary.totalRevenue), sub: 'All time', gradient: 'stat-purple', link: '/reports' },
  ];

  const quickActions = [
    { label: 'Record Sale', path: '/sales', primary: true },
    { label: 'Add Product', path: '/products' },
    { label: 'New Customer', path: '/customers' },
    { label: 'View Reports', path: '/reports' },
  ];

  const maxSaleAmount = Math.max(
    ...summary.recentSales.map((s) => parseFloat(s.total_price)),
    1
  );

  return (
    <div className="dashboard">
      <section className="dashboard-hero">
        <div className="hero-content">
          <span className="hero-greeting">{getGreeting()}</span>
          <h1 className="hero-title">SmartShop Overview</h1>
          <p className="hero-desc">
            Monitor your electronics sales, inventory, and customer activity in real time.
          </p>
        </div>
        <div className="hero-actions">
          {quickActions.map((action) => (
            <Link
              key={action.label}
              to={action.path}
              className={`quick-action-btn ${action.primary ? 'primary' : ''}`}
            >
              {action.label}
            </Link>
          ))}
        </div>
      </section>

      <div className="stats-grid">
        {stats.map((stat) => (
          <Link key={stat.label} to={stat.link} className={`stat-card ${stat.gradient}`}>
            <div className="stat-card-top">
              <span className="stat-trend">Active</span>
            </div>
            <div className="stat-card-body">
              <span className="stat-value">{stat.value}</span>
              <span className="stat-label">{stat.label}</span>
              <span className="stat-sub">{stat.sub}</span>
            </div>
          </Link>
        ))}
      </div>

      <div className="dashboard-grid">
        <div className="panel panel-sales">
          <div className="panel-header">
            <div>
              <h3>Recent Sales</h3>
              <p>Latest transactions across your store</p>
            </div>
            <Link to="/sales" className="panel-link">View all</Link>
          </div>

          {summary.recentSales.length === 0 ? (
            <div className="panel-empty">
              <p>No sales recorded yet</p>
              <Link to="/sales" className="btn btn-primary btn-sm">Record first sale</Link>
            </div>
          ) : (
            <div className="sales-list">
              {summary.recentSales.map((sale) => (
                <div key={sale.sale_id} className="sale-row">
                  <div className="sale-avatar">
                    {sale.customer_name.charAt(0)}
                  </div>
                  <div className="sale-info">
                    <span className="sale-customer">{sale.customer_name}</span>
                    <span className="sale-product">{sale.product_name}</span>
                  </div>
                  <div className="sale-meta">
                    <span className="sale-amount">{formatCurrency(sale.total_price)}</span>
                    <span className="sale-date">{formatDate(sale.sale_date)}</span>
                  </div>
                  <div
                    className="sale-bar"
                    style={{ width: `${(parseFloat(sale.total_price) / maxSaleAmount) * 100}%` }}
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="dashboard-side">
          <div className="panel panel-revenue">
            <div className="panel-header">
              <h3>Revenue Snapshot</h3>
            </div>
            <div className="revenue-display">
              <span className="revenue-amount">{formatCurrency(summary.totalRevenue)}</span>
              <span className="revenue-label">Total earnings</span>
            </div>
            <div className="revenue-breakdown">
              <div className="breakdown-item">
                <span>Sales count</span>
                <strong>{summary.totalSales}</strong>
              </div>
              <div className="breakdown-item">
                <span>Products</span>
                <strong>{summary.totalProducts}</strong>
              </div>
              <div className="breakdown-item">
                <span>Customers</span>
                <strong>{summary.totalCustomers}</strong>
              </div>
            </div>
          </div>

          <div className="panel panel-stock">
            <div className="panel-header">
              <div>
                <h3>Stock Alerts</h3>
                <p>Items running low</p>
              </div>
              <Link to="/products" className="panel-link">Manage</Link>
            </div>

            {summary.lowStock.length === 0 ? (
              <div className="stock-ok">
                <p>All products well stocked</p>
              </div>
            ) : (
              <ul className="stock-alert-list">
                {summary.lowStock.map((product) => {
                  const pct = Math.min((product.quantity / 10) * 100, 100);
                  return (
                    <li key={product.product_id} className="stock-alert-item">
                      <div className="stock-alert-top">
                        <span className="stock-name">{product.product_name}</span>
                        <span className={`stock-qty ${product.quantity === 0 ? 'critical' : 'low'}`}>
                          {product.quantity} units
                        </span>
                      </div>
                      <div className="stock-bar-track">
                        <div
                          className={`stock-bar-fill ${product.quantity === 0 ? 'critical' : 'low'}`}
                          style={{ width: `${pct}%` }}
                        />
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
