import { fmt, fmtD, NOW, toLocal } from '../utils/helpers';
import { Badge, ClientName, StockBadge } from '../components/ui/Badge';
import { BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

export default function Dashboard({ products, clients, orders }) {
  const confirmed = orders.filter((o) => o.status === 'confirmed');
  const today = NOW();
  const tRev = confirmed.filter((o) => toLocal(o.order_date) === today).reduce((s, o) => s + parseFloat(o.total), 0);
  const ordersToday = confirmed.filter((o) => toLocal(o.order_date) === today).length;
  const rev = confirmed.reduce((s, o) => s + parseFloat(o.total), 0);
  const cogs = confirmed.reduce((s, o) =>
    s + (o.items || []).reduce((x, i) => {
      const p = products.find((pp) => pp.id === i.product_id);
      return x + (p ? parseFloat(p.cost_price) * i.qty : 0);
    }, 0), 0);
  const vipCount = clients.filter((c) => !c.is_deleted && c.is_vip).length;
  const low = products.filter((p) => p.stock_qty <= p.low_threshold);
  const recent = [...orders].sort((a, b) => (b.order_date || '').localeCompare(a.order_date || '')).slice(0, 5);

  const fuList = [];
  orders.forEach((o) =>
    (o.followUps || []).filter((f) => f.status === 'pending').forEach((f) =>
      fuList.push({ ...f, oid: o.id, cid: o.client_id })
    )
  );
  fuList.sort((a, b) => (a.follow_date || '').localeCompare(b.follow_date || ''));

  // Build revenue chart data (last 7 days)
  const revenueByDay = {};
  for (let i = 6; i >= 0; i--) {
    const d = new Date(); d.setDate(d.getDate() - i);
    const ds = toLocal(d);
    revenueByDay[ds] = { date: ds, label: d.toLocaleDateString('en-US', { weekday: 'short' }), revenue: 0, orders: 0 };
  }
  confirmed.forEach((o) => {
    const d = toLocal(o.order_date);
    if (revenueByDay[d]) { revenueByDay[d].revenue += parseFloat(o.total); revenueByDay[d].orders += 1; }
  });
  const chartData = Object.values(revenueByDay);

  // Top products this period
  const prodSales = {};
  confirmed.forEach((o) => (o.items || []).forEach((i) => {
    if (!prodSales[i.product_id]) prodSales[i.product_id] = 0;
    prodSales[i.product_id] += i.qty;
  }));
  const topProds = Object.entries(prodSales)
    .map(([id, qty]) => ({ name: products.find((p) => p.id === id)?.name?.slice(0, 10) || '?', qty }))
    .sort((a, b) => b.qty - a.qty).slice(0, 5);

  const stats = [
    { l: 'Today', v: fmt(tRev), c: 'border-l-gr' },
    { l: 'Orders Today', v: ordersToday, c: 'border-l-ac' },
    { l: 'VIP Clients', v: vipCount, c: 'border-l-gold' },
    { l: 'Low Stock', v: low.length, c: low.length ? 'border-l-rd' : 'border-l-gr' },
    { l: 'Pending Follow-ups', v: fuList.length, c: fuList.length ? 'border-l-or' : 'border-l-gr' },
    { l: 'Gross Profit', v: fmt(rev - cogs), c: 'border-l-gr' },
  ];

  const tooltipStyle = { contentStyle: { background: '#12161e', border: '1px solid #262d3d', borderRadius: 8, fontSize: 12, color: '#e8ecf4' } };

  return (
    <div>
      <h1 className="text-xl font-bold mb-0.5">Dashboard</h1>
      <p className="text-t2 text-xs mb-5">Business overview</p>

      <div className="flex gap-2.5 flex-wrap mb-5">
        {stats.map((s, i) => (
          <div key={i} className={`bg-s1 border border-bd rounded-[10px] py-3.5 px-4 flex-1 min-w-[130px] border-l-[3px] ${s.c}`}>
            <div className="text-[10px] text-t2 mb-0.5">{s.l}</div>
            <div className="text-lg font-bold">{s.v}</div>
          </div>
        ))}
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 mb-5">
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">📈 Revenue (Last 7 Days)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" stroke="#262d3d" />
              <XAxis dataKey="label" tick={{ fontSize: 10, fill: '#8696ad' }} />
              <YAxis tick={{ fontSize: 10, fill: '#8696ad' }} />
              <Tooltip {...tooltipStyle} />
              <Line type="monotone" dataKey="revenue" stroke="#3b82f6" strokeWidth={2} dot={{ r: 3 }} name="Revenue ($)" />
            </LineChart>
          </ResponsiveContainer>
        </div>
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">🏆 Top Products</h3>
          {topProds.length > 0 ? (
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={topProds}>
                <CartesianGrid strokeDasharray="3 3" stroke="#262d3d" />
                <XAxis dataKey="name" tick={{ fontSize: 9, fill: '#8696ad' }} />
                <YAxis tick={{ fontSize: 10, fill: '#8696ad' }} />
                <Tooltip {...tooltipStyle} />
                <Bar dataKey="qty" fill="#22c55e" radius={[4, 4, 0, 0]} name="Qty Sold" />
              </BarChart>
            </ResponsiveContainer>
          ) : <p className="text-t2 text-xs text-center py-8">No sales data yet</p>}
        </div>
      </div>

      <div className="flex gap-3 flex-wrap">
        <div className="bg-s1 border border-bd rounded-[10px] p-4 mb-3 flex-[2] min-w-[280px]">
          <h3 className="text-[13px] font-bold mb-2.5">Recent Orders</h3>
          <div className="overflow-x-auto -mx-1">
          <table className="w-full min-w-[420px]">
            <thead>
              <tr>
                {['#', 'Client', 'Date', 'Total', 'Status'].map((h) => (
                  <th key={h} className="text-left p-2 text-[10px] font-bold uppercase text-t2 border-b border-bd">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {recent.map((o) => {
                const cl = clients.find((c) => c.id === o.client_id);
                return (
                  <tr key={o.id}>
                    <td className="p-2 border-b border-bd text-xs text-t2">#{o.id}</td>
                    <td className="p-2 border-b border-bd text-[13px]"><ClientName client={cl} /></td>
                    <td className="p-2 border-b border-bd text-[13px]">{fmtD(o.order_date)}</td>
                    <td className="p-2 border-b border-bd text-[13px] font-bold">{fmt(o.total)}</td>
                    <td className="p-2 border-b border-bd text-[13px]"><Badge s={o.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          </div>
        </div>

        <div className="flex flex-col gap-3 flex-1 min-w-[210px]">
          <div className="bg-s1 border border-bd rounded-[10px] p-4">
            <h3 className="text-[13px] font-bold mb-2">Low Stock Alerts</h3>
            {low.length === 0 ? (
              <p className="text-t2 text-xs">All good ✓</p>
            ) : (
              low.map((p) => (
                <div key={p.id} className="flex justify-between py-1 border-b border-bd">
                  <span className="font-semibold text-xs">{p.name}</span>
                  <StockBadge q={p.stock_qty} t={p.low_threshold} />
                </div>
              ))
            )}
          </div>

          <div className="bg-s1 border border-bd rounded-[10px] p-4">
            <h3 className="text-[13px] font-bold mb-2">Follow-ups</h3>
            {fuList.length === 0 ? (
              <p className="text-t2 text-xs">None</p>
            ) : (
              fuList.slice(0, 4).map((f) => {
                const cl = clients.find((c) => c.id === f.cid);
                return (
                  <div key={f.id} className="py-1 border-b border-bd text-[11px]">
                    <span className="font-semibold">{cl?.name}</span>
                    <div className="flex justify-between text-t2">
                      <span>{f.note?.slice(0, 25)}...</span>
                      <span className={`font-semibold ${(f.follow_date || '') < NOW() ? 'text-rd' : 'text-ac'}`}>
                        {fmtD(f.follow_date)}
                      </span>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
