import { useEffect, useState } from 'react';
import { shire } from '@/api/shireClient';
import { Link } from 'react-router-dom';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';
import { AlertTriangle } from 'lucide-react';
import { format, startOfMonth, endOfMonth } from 'date-fns';

const StatCard = ({ label, value, sub }) => (
  <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
    <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">{label}</p>
    <p className="text-2xl font-bold text-gray-900 mt-1">{value ?? '—'}</p>
    {sub && <p className="text-xs text-gray-400 mt-0.5">{sub}</p>}
  </div>
);

const MKT_BADGE = {
  Etsy: 'bg-orange-100 text-orange-700',
  Square: 'bg-green-100 text-green-700',
  eBay: 'bg-blue-100 text-blue-700',
};

const STATUS_PILL = {
  Pending: 'bg-yellow-100 text-yellow-700',
  Processing: 'bg-blue-100 text-blue-700',
  Shipped: 'bg-purple-100 text-purple-700',
  Delivered: 'bg-green-100 text-green-700',
  Cancelled: 'bg-red-100 text-red-700',
  Refunded: 'bg-gray-100 text-gray-600',
};

export default function Dashboard() {
  const [products, setProducts] = useState([]);
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      shire.entities.Product.list('-created_date', 500),
      shire.entities.Order.list('-order_date', 500),
    ]).then(([p, o]) => {
      setProducts(p);
      setOrders(o);
      setLoading(false);
    });
  }, []);

  const now = new Date();
  const monthStart = format(startOfMonth(now), 'yyyy-MM-dd');
  const monthEnd = format(endOfMonth(now), 'yyyy-MM-dd');

  const ordersThisMonth = orders.filter(o =>
    o.order_date >= monthStart && o.order_date <= monthEnd
  );
  const revenueThisMonth = ordersThisMonth.reduce((s, o) => s + (o.total || 0), 0);

  const missing = products.filter(p => !p.etsy_url || !p.square_url || !p.ebay_url);

  // Category chart data
  const catMap = {};
  products.forEach(p => {
    const c = p.category || 'Uncategorised';
    catMap[c] = (catMap[c] || 0) + 1;
  });
  const chartData = Object.entries(catMap)
    .sort((a, b) => b[1] - a[1])
    .map(([name, count]) => ({ name, count }));

  const recentOrders = [...orders]
    .sort((a, b) => (b.order_date || '').localeCompare(a.order_date || ''))
    .slice(0, 5);

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

  return (
    <div className="p-6 md:p-8 max-w-7xl mx-auto space-y-8">
      <h1 className="text-2xl font-bold text-gray-900">Welcome back, Shire 3D 👋</h1>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <StatCard label="Total Products" value={products.length} />
        <StatCard label="Listed on Etsy" value={products.filter(p => p.etsy_url).length} />
        <StatCard label="Listed on Square" value={products.filter(p => p.square_url).length} />
        <StatCard label="Listed on eBay" value={products.filter(p => p.ebay_url).length} />
        <StatCard label="Orders This Month" value={ordersThisMonth.length} />
        <StatCard label="Revenue This Month" value={`$${revenueThisMonth.toFixed(2)}`} sub="AUD" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Category chart */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Products by Category</h2>
          {chartData.length === 0 ? (
            <p className="text-gray-400 text-sm py-8 text-center">No products yet.</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={chartData} layout="vertical" margin={{ left: 0, right: 20 }}>
                <XAxis type="number" allowDecimals={false} tick={{ fontSize: 12 }} />
                <YAxis type="category" dataKey="name" width={110} tick={{ fontSize: 12 }} />
                <Tooltip />
                <Bar dataKey="count" radius={[0, 4, 4, 0]}>
                  {chartData.map((_, i) => (
                    <Cell key={i} fill="#f97316" opacity={1 - i * 0.08} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Missing listings */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center gap-2 mb-4">
            <AlertTriangle size={16} className="text-amber-500" />
            <h2 className="font-semibold text-gray-900">Missing Listings ({missing.length})</h2>
          </div>
          {missing.length === 0 ? (
            <p className="text-green-600 text-sm">All products are listed on every marketplace! 🎉</p>
          ) : (
            <div className="space-y-2 max-h-56 overflow-y-auto">
              {missing.map(p => {
                const gaps = [];
                if (!p.etsy_url) gaps.push('Etsy');
                if (!p.square_url) gaps.push('Square');
                if (!p.ebay_url) gaps.push('eBay');
                return (
                  <div key={p.id} className="flex items-center justify-between bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">
                    <div>
                      <p className="text-sm font-medium text-gray-800 truncate max-w-[180px]">{p.title}</p>
                      <p className="text-xs text-amber-600">Missing: {gaps.join(', ')}</p>
                    </div>
                    <Link
                      to={`/products?edit=${p.id}`}
                      className="text-xs font-medium px-2 py-1 rounded text-white"
                      style={{ background: '#f97316' }}
                    >
                      Add URL
                    </Link>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Recent Orders */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-6 py-4 border-b border-gray-100">
          <h2 className="font-semibold text-gray-900">Recent Orders</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
                <th className="px-6 py-3 text-left">Order #</th>
                <th className="px-6 py-3 text-left">Marketplace</th>
                <th className="px-6 py-3 text-left">Customer</th>
                <th className="px-6 py-3 text-left">Total</th>
                <th className="px-6 py-3 text-left">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {recentOrders.length === 0 ? (
                <tr><td colSpan={5} className="px-6 py-8 text-center text-gray-400">No orders yet.</td></tr>
              ) : (
                recentOrders.map(o => (
                  <tr key={o.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-3 font-mono text-gray-700">{o.order_number}</td>
                    <td className="px-6 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${MKT_BADGE[o.marketplace] || 'bg-gray-100 text-gray-600'}`}>
                        {o.marketplace}
                      </span>
                    </td>
                    <td className="px-6 py-3 text-gray-700">{o.customer_name}</td>
                    <td className="px-6 py-3 font-semibold text-gray-800">${(o.total || 0).toFixed(2)}</td>
                    <td className="px-6 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_PILL[o.status] || 'bg-gray-100 text-gray-600'}`}>
                        {o.status}
                      </span>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
