import React, { useState, useEffect } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import api from '../utils/api';

const COLORS = ['#0052FF', '#FF6B35', '#00C48C', '#FFAB00'];

const formatRWF = v => `${Number(v).toLocaleString()} RWF`;

export default function Dashboard() {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/reports/dashboard')
      .then(r => setStats(r.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div className="spinner" />;
  if (!stats) return <div className="empty-state"><div className="empty-icon">⚠️</div><div>Failed to load dashboard</div></div>;

  const revenueData = stats.recentSales.map(d => ({
    date: new Date(d.date).toLocaleDateString('en-RW', { month: 'short', day: 'numeric' }),
    revenue: parseFloat(d.revenue)
  }));

  const categoryData = stats.categoryStats.map(c => ({
    name: c.category,
    value: parseFloat(c.revenue) || 0
  }));

  return (
    <div>
      {/* Stats */}
      <div className="stats-grid">
        <div className="stat-card blue">
          <div className="stat-icon blue">📦</div>
          <div className="stat-value">{stats.total_products}</div>
          <div className="stat-label">Total Products</div>
        </div>
        <div className="stat-card orange">
          <div className="stat-icon orange">👥</div>
          <div className="stat-value">{stats.total_customers}</div>
          <div className="stat-label">Registered Customers</div>
        </div>
        <div className="stat-card green">
          <div className="stat-icon green">🛒</div>
          <div className="stat-value">{stats.total_sales}</div>
          <div className="stat-label">Total Sales</div>
        </div>
        <div className="stat-card yellow">
          <div className="stat-icon yellow">💰</div>
          <div className="stat-value" style={{ fontSize: 18 }}>{Number(stats.total_revenue).toLocaleString()}</div>
          <div className="stat-label">Revenue (RWF)</div>
        </div>
      </div>

      {/* Charts */}
      <div className="charts-grid">
        <div className="card">
          <div className="card-header">
            <span className="card-title">Revenue — Last 7 Days</span>
          </div>
          <div className="card-body" style={{ paddingTop: 8 }}>
            {revenueData.length === 0 ? (
              <div className="empty-state" style={{ padding: 30 }}>
                <div className="empty-icon">📊</div>
                <div className="empty-title">No sales in the last 7 days</div>
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={220}>
                <AreaChart data={revenueData}>
                  <defs>
                    <linearGradient id="colorRev" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#0052FF" stopOpacity={0.15} />
                      <stop offset="95%" stopColor="#0052FF" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#F0F2F5" />
                  <XAxis dataKey="date" tick={{ fontSize: 11, fill: '#8B949E' }} />
                  <YAxis tick={{ fontSize: 11, fill: '#8B949E' }} tickFormatter={v => `${(v/1000).toFixed(0)}K`} />
                  <Tooltip formatter={v => [formatRWF(v), 'Revenue']} />
                  <Area type="monotone" dataKey="revenue" stroke="#0052FF" strokeWidth={2.5} fill="url(#colorRev)" dot={{ fill: '#0052FF', r: 3 }} />
                </AreaChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <span className="card-title">Sales by Category</span>
          </div>
          <div className="card-body" style={{ paddingTop: 8 }}>
            {categoryData.every(d => d.value === 0) ? (
              <div className="empty-state" style={{ padding: 30 }}>
                <div className="empty-icon">🍕</div>
                <div className="empty-title">No category data yet</div>
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={220}>
                <PieChart>
                  <Pie data={categoryData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} label={({ name, percent }) => `${(percent * 100).toFixed(0)}%`} labelLine={false}>
                    {categoryData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip formatter={v => formatRWF(v)} />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>
      </div>

      {/* Bottom Row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Top Products */}
        <div className="card">
          <div className="card-header">
            <span className="card-title">🏆 Top Selling Products</span>
          </div>
          <div className="table-wrapper">
            {stats.topProducts.length === 0 ? (
              <div className="empty-state" style={{ padding: 30 }}>
                <div className="empty-title">No sales recorded yet</div>
              </div>
            ) : (
              <table>
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Product</th>
                    <th>Sold</th>
                    <th>Revenue</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.topProducts.map((p, i) => (
                    <tr key={i}>
                      <td><span style={{ background: 'var(--primary-light)', color: 'var(--primary)', borderRadius: 4, padding: '2px 7px', fontSize: 11, fontWeight: 700 }}>{i + 1}</span></td>
                      <td style={{ fontWeight: 500 }}>{p.product_name}</td>
                      <td>{p.total_sold}</td>
                      <td style={{ fontWeight: 600, color: 'var(--success)' }}>{Number(p.revenue).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* Category Stats */}
        <div className="card">
          <div className="card-header">
            <span className="card-title">📊 Category Performance</span>
          </div>
          <div className="card-body">
            {stats.categoryStats.map((c, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < stats.categoryStats.length - 1 ? '1px solid var(--border-light)' : 'none' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 10, height: 10, borderRadius: '50%', background: COLORS[i % COLORS.length] }} />
                  <span style={{ fontWeight: 500 }}>{c.category}</span>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{c.sales_count} sales</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{Number(c.revenue).toLocaleString()} RWF</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
