import { useEffect, useState } from 'react';
import api from '../services/api';
import { formatCurrency, formatNumber } from '../utils/formatters';
import { CurrencyDollarIcon, ShoppingBagIcon, CubeIcon, ChartBarIcon } from '@heroicons/react/24/outline';

function StatCard({ icon: Icon, label, value, sub, color }) {
  return (
    <div className="card p-5 flex items-start gap-4">
      <div className={`p-3 rounded-xl ${color}`}>
        <Icon className="w-6 h-6 text-white" />
      </div>
      <div>
        <p className="text-sm text-gray-500">{label}</p>
        <p className="text-xl font-bold text-gray-900 mt-0.5">{value}</p>
        {sub && <p className="text-xs text-gray-400 mt-0.5">{sub}</p>}
      </div>
    </div>
  );
}

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

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

  if (loading) return (
    <div className="flex items-center justify-center h-64">
      <div className="animate-spin w-8 h-8 border-4 border-orange-500 border-t-transparent rounded-full" />
    </div>
  );

  const today = data?.today || {};
  const stock = data?.stock || {};
  const topProducts = data?.top_products || [];

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-lg font-semibold text-gray-900">Ringkasan Hari Ini</h2>
        <p className="text-sm text-gray-500">{new Date().toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
        <StatCard icon={CurrencyDollarIcon} label="Total Penjualan" value={formatCurrency(today.total_revenue)} color="bg-orange-500" />
        <StatCard icon={ShoppingBagIcon} label="Total Transaksi" value={formatNumber(today.total_transactions)} sub="transaksi hari ini" color="bg-blue-500" />
        <StatCard icon={CubeIcon} label="Total Stok" value={formatNumber(stock.total_stock)} sub={`${stock.low_stock} item hampir habis`} color="bg-emerald-500" />
        <StatCard icon={ChartBarIcon} label="Est. Laba" value={formatCurrency(today.estimated_profit)} sub="estimasi 30%" color="bg-violet-500" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="card">
          <div className="px-5 py-4 border-b">
            <h3 className="font-semibold text-gray-800">Produk Terlaris Hari Ini</h3>
          </div>
          {topProducts.length === 0 ? (
            <div className="p-8 text-center text-gray-400 text-sm">Belum ada transaksi hari ini</div>
          ) : (
            <div className="divide-y divide-gray-100">
              {topProducts.map((p, i) => (
                <div key={i} className="px-5 py-3 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span className="w-6 h-6 rounded-full bg-orange-100 text-orange-600 text-xs font-bold flex items-center justify-center flex-shrink-0">{i + 1}</span>
                    <span className="text-sm font-medium text-gray-800">{p.item_name}</span>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-semibold text-gray-900">{formatCurrency(p.total_revenue)}</p>
                    <p className="text-xs text-gray-400">Qty: {formatNumber(p.total_qty)}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card">
          <div className="px-5 py-4 border-b">
            <h3 className="font-semibold text-gray-800">Info Stok</h3>
          </div>
          <div className="p-5 space-y-3">
            <div className="flex justify-between items-center py-2 border-b border-gray-100">
              <span className="text-sm text-gray-600">Total Produk Aktif</span>
              <span className="font-semibold text-gray-900">{formatNumber(stock.total_products)}</span>
            </div>
            <div className="flex justify-between items-center py-2 border-b border-gray-100">
              <span className="text-sm text-gray-600">Total Stok</span>
              <span className="font-semibold text-gray-900">{formatNumber(stock.total_stock)}</span>
            </div>
            <div className="flex justify-between items-center py-2">
              <span className="text-sm text-gray-600">Stok Hampir Habis ({'≤'}5)</span>
              <span className={`font-semibold ${parseInt(stock.low_stock) > 0 ? 'text-red-600' : 'text-green-600'}`}>
                {formatNumber(stock.low_stock)} item
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
