import { useState, useEffect } from 'react';
import api from '../utils/api';
import { fmt, fmtD, toLocal, REFERRAL_BONUS } from '../utils/helpers';
import { Icons } from '../components/icons/Icons';
import { VipBadge } from '../components/ui/Badge';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import jsPDF from 'jspdf';
import 'jspdf-autotable';

const COLORS = ['#3b82f6', '#22c55e', '#eab308', '#ef4444', '#a78bfa', '#f97316', '#f59e0b', '#06b6d4'];

export default function Reports({ products, clients, orders }) {
  const [range, setRange] = useState('all');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const [data, setData] = useState(null);

  const fetchReport = async () => {
    try {
      const params = new URLSearchParams({ range });
      if (range === 'custom' && from && to) { params.set('from', from); params.set('to', to); }
      const res = await api.get(`/reports?${params}`);
      setData(res.data);
    } catch {}
  };

  useEffect(() => { fetchReport(); }, [range, from, to]);

  const downloadExcel = async () => {
    try {
      const res = await api.get('/reports/export', { responseType: 'blob' });
      const url = URL.createObjectURL(new Blob([res.data]));
      const a = document.createElement('a'); a.href = url; a.download = 'PeptideOS-Report.xlsx'; a.click();
    } catch {}
  };

  const downloadPDF = async () => {
    try {
      const res = await api.get('/reports/export?format=json');
      const rows = res.data;
      const doc = new jsPDF({ orientation: 'landscape' });

      // Title
      doc.setFontSize(18);
      doc.setTextColor(59, 130, 246);
      doc.text('PeptideOS - Sales Report', 14, 18);
      doc.setFontSize(10);
      doc.setTextColor(100);
      doc.text(`Generated: ${new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}`, 14, 25);

      // Summary
      if (data) {
        doc.setFontSize(11);
        doc.setTextColor(40);
        const sumY = 33;
        doc.text(`Revenue: ${fmt(data.revenue)}`, 14, sumY);
        doc.text(`COGS: ${fmt(data.cogs)}`, 80, sumY);
        doc.text(`Gross Profit: ${fmt(data.grossProfit)}`, 140, sumY);
        doc.text(`Net Profit: ${fmt(data.netProfit)}`, 210, sumY);
      }

      // Orders table
      doc.autoTable({
        startY: 40,
        head: [['Order ID', 'Date', 'Client', 'Items', 'Subtotal', 'Discount', 'Total', 'Payment', 'Status']],
        body: rows.map((r) => [
          r.id,
          r.date,
          r.client,
          r.items.length > 40 ? r.items.slice(0, 40) + '...' : r.items,
          `$${r.subtotal.toFixed(2)}`,
          r.discount > 0 ? `-$${r.discount.toFixed(2)} (${r.discountPct}%)` : '-',
          `$${r.total.toFixed(2)}`,
          r.paymentMethod,
          r.status,
        ]),
        styles: { fontSize: 8, cellPadding: 2 },
        headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold' },
        alternateRowStyles: { fillColor: [245, 247, 250] },
        columnStyles: {
          0: { cellWidth: 18 },
          1: { cellWidth: 25 },
          2: { cellWidth: 30 },
          3: { cellWidth: 55 },
          4: { cellWidth: 22, halign: 'right' },
          5: { cellWidth: 28, halign: 'right' },
          6: { cellWidth: 22, halign: 'right', fontStyle: 'bold' },
          7: { cellWidth: 25 },
          8: { cellWidth: 20 },
        },
      });

      // Footer
      const pageCount = doc.internal.getNumberOfPages();
      for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(150);
        doc.text(`PeptideOS Report — Page ${i} of ${pageCount}`, doc.internal.pageSize.getWidth() / 2, doc.internal.pageSize.getHeight() - 8, { align: 'center' });
      }

      doc.save('PeptideOS-Report.pdf');
    } catch (err) {
      console.error('PDF export error:', err);
    }
  };

  if (!data) return <div className="text-t2 p-8 text-center">Loading reports...</div>;

  // Build sales trend data from orders
  const salesByDate = {};
  orders.filter((o) => o.status === 'confirmed').forEach((o) => {
    const d = toLocal(o.order_date);
    if (!salesByDate[d]) salesByDate[d] = { date: d, revenue: 0, orders: 0 };
    salesByDate[d].revenue += parseFloat(o.total);
    salesByDate[d].orders += 1;
  });
  const salesTrend = Object.values(salesByDate).sort((a, b) => a.date.localeCompare(b.date)).slice(-30);

  // Slow-moving products (least sold)
  const productSales = {};
  orders.filter((o) => o.status === 'confirmed').forEach((o) => (o.items || []).forEach((i) => {
    if (!productSales[i.product_id]) productSales[i.product_id] = 0;
    productSales[i.product_id] += i.qty;
  }));
  const slowMoving = products.map((p) => ({ ...p, sold: productSales[p.id] || 0 })).sort((a, b) => a.sold - b.sold).slice(0, 5);

  // VIP vs Regular
  const vipClients = clients.filter((c) => !c.is_deleted && c.is_vip).length;
  const regularClients = clients.filter((c) => !c.is_deleted && !c.is_vip).length;
  const vipRevenue = orders.filter((o) => o.status === 'confirmed').reduce((s, o) => {
    const cl = clients.find((c) => c.id === o.client_id);
    return cl?.is_vip ? s + parseFloat(o.total) : s;
  }, 0);
  const regularRevenue = data.revenue - vipRevenue;
  const vipData = [
    { name: 'VIP', clients: vipClients, revenue: vipRevenue },
    { name: 'Regular', clients: regularClients, revenue: regularRevenue },
  ];

  // Client lifetime value
  const clientLTV = {};
  orders.filter((o) => o.status === 'confirmed').forEach((o) => {
    if (!clientLTV[o.client_id]) clientLTV[o.client_id] = { spent: 0, orders: 0 };
    clientLTV[o.client_id].spent += parseFloat(o.total);
    clientLTV[o.client_id].orders += 1;
  });
  const clientRankings = Object.entries(clientLTV)
    .map(([id, d]) => { const c = clients.find((x) => x.id === id); return { name: c?.name || '?', is_vip: c?.is_vip, ...d }; })
    .sort((a, b) => b.spent - a.spent).slice(0, 10);

  // Referral performance
  const referralData = {};
  orders.filter((o) => o.status === 'confirmed' && o.referral_from).forEach((o) => {
    if (!referralData[o.referral_from]) referralData[o.referral_from] = { referrals: 0, revenue: 0, bonus: 0 };
    referralData[o.referral_from].referrals += 1;
    referralData[o.referral_from].revenue += parseFloat(o.total);
    referralData[o.referral_from].bonus += REFERRAL_BONUS;
  });
  const referralPerf = Object.entries(referralData)
    .map(([id, d]) => { const c = clients.find((x) => x.id === id); return { name: c?.name || '?', ...d }; })
    .sort((a, b) => b.referrals - a.referrals);

  // Payment methods pie data
  const payPie = Object.entries(data.paymentMethods || {}).map(([name, value]) => ({ name, value }));

  // Top products bar data
  const topProdBar = (data.topProducts || []).map((p) => ({ name: p.name?.slice(0, 12), qty: p.qty, revenue: p.revenue }));

  const stats = [
    { l: 'Revenue', v: fmt(data.revenue), c: 'border-l-ac' },
    { l: 'COGS', v: fmt(data.cogs), c: 'border-l-t2' },
    { l: 'Gross Profit', v: fmt(data.grossProfit), c: 'border-l-gr' },
    { l: 'Discounts', v: fmt(data.discounts), c: 'border-l-yl' },
    { l: 'Referral Bonus', v: fmt(data.referralBonus), c: 'border-l-pr' },
    { l: 'Net Profit', v: fmt(data.netProfit), c: data.netProfit >= 0 ? 'border-l-gr' : 'border-l-rd' },
    { l: 'Transactions', v: data.totalOrders, c: 'border-l-ac' },
    { l: 'Cancelled', v: data.cancelledCount, c: 'border-l-yl' },
  ];

  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">Sales Report & Analytics</h1>
      <p className="text-t2 text-xs mb-5">Comprehensive business performance</p>

      {/* Filters */}
      <div className="flex gap-1.5 mb-4 flex-wrap items-center">
        {['all', 'today', 'week', 'month', 'custom'].map((r) => (
          <button key={r} className={`px-3 py-1.5 rounded-md text-xs font-semibold border ${range === r ? 'bg-ac text-white border-ac' : 'border-bd text-t2 hover:bg-s2'}`} onClick={() => setRange(r)}>{r === 'all' ? 'All Time' : r[0].toUpperCase() + r.slice(1)}</button>
        ))}
        {range === 'custom' && (<>
          <input type="date" className="p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] w-[130px]" value={from} onChange={(e) => setFrom(e.target.value)} />
          <span className="text-t2">→</span>
          <input type="date" className="p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] w-[130px]" value={to} onChange={(e) => setTo(e.target.value)} />
        </>)}
        <div className="flex gap-2 ml-auto">
          <button className="bg-gr text-white px-4 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1.5 hover:bg-gr/90" onClick={downloadExcel}><Icons.Download /> Excel</button>
          <button className="bg-rd text-white px-4 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1.5 hover:bg-rd/90" onClick={downloadPDF}><Icons.Download /> PDF</button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-[repeat(auto-fill,minmax(140px,1fr))] gap-2.5 mb-5">
        {stats.map((s, i) => (
          <div key={i} className={`bg-s1 border border-bd rounded-[10px] py-3.5 px-4 border-l-[3px] ${s.c}`}>
            <div className="text-[10px] text-t2">{s.l}</div>
            <div className="text-[17px] font-bold">{s.v}</div>
          </div>
        ))}
      </div>

      {/* Sales Trend Chart */}
      {salesTrend.length > 1 && (
        <div className="bg-s1 border border-bd rounded-[10px] p-4 mb-3">
          <h3 className="text-[13px] font-bold mb-3">📈 Sales Trend</h3>
          <ResponsiveContainer width="100%" height={250}>
            <LineChart data={salesTrend}>
              <CartesianGrid strokeDasharray="3 3" stroke="#262d3d" />
              <XAxis dataKey="date" tick={{ fontSize: 10, fill: '#8696ad' }} tickFormatter={(v) => v.slice(5)} />
              <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="grid grid-cols-1 lg:grid-cols-2 gap-3 mb-3">
        {/* Top-Selling Products */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">🏆 Top-Selling Products</h3>
          {topProdBar.length > 0 ? (
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={topProdBar}>
                <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="#3b82f6" radius={[4, 4, 0, 0]} name="Qty Sold" />
              </BarChart>
            </ResponsiveContainer>
          ) : <p className="text-t2 text-xs">No data</p>}
        </div>

        {/* Slow-Moving Products */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">🐌 Slow-Moving Products</h3>
          {slowMoving.map((p, i) => (
            <div key={p.id} className="flex justify-between py-1.5 border-b border-bd text-xs">
              <span className="font-semibold">{i + 1}. {p.name}</span>
              <div className="flex gap-3">
                <span className="text-t2">Stock: {p.stock_qty}</span>
                <span className={p.sold === 0 ? 'text-rd font-bold' : 'text-yl'}>{p.sold} sold</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 mb-3">
        {/* Client Rankings (LTV) */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">👑 Client Rankings (Lifetime Value)</h3>
          {clientRankings.map((c, i) => (
            <div key={i} className="flex justify-between items-center py-1.5 border-b border-bd text-xs">
              <div className="flex items-center gap-2">
                <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold ${i < 3 ? 'bg-gold text-black' : 'bg-s2 text-t2'}`}>{i + 1}</span>
                <span className={`font-semibold ${c.is_vip ? 'text-gold' : ''}`}>{c.name}</span>
                {c.is_vip ? <VipBadge /> : null}
              </div>
              <div className="text-right">
                <div className="font-bold text-gr">{fmt(c.spent)}</div>
                <div className="text-[9px] text-t2">{c.orders} orders</div>
              </div>
            </div>
          ))}
        </div>

        {/* VIP vs Regular */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">⭐ VIP vs Regular</h3>
          <div className="flex gap-4 mb-3">
            {vipData.map((d, i) => (
              <div key={i} className="flex-1 bg-s2 rounded-md p-3 border border-bd text-center">
                <div className="text-[10px] text-t2 mb-1">{d.name}</div>
                <div className="text-lg font-bold" style={{ color: i === 0 ? '#f59e0b' : '#8696ad' }}>{d.clients}</div>
                <div className="text-[10px] text-t2">clients</div>
                <div className="text-sm font-bold text-gr mt-1">{fmt(d.revenue)}</div>
                <div className="text-[9px] text-t2">revenue</div>
              </div>
            ))}
          </div>
          <ResponsiveContainer width="100%" height={160}>
            <PieChart>
              <Pie data={vipData} cx="50%" cy="50%" outerRadius={60} dataKey="revenue" label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`} labelLine={false}>
                {vipData.map((_, i) => <Cell key={i} fill={i === 0 ? '#f59e0b' : '#8696ad'} />)}
              </Pie>
              <Tooltip {...tooltipStyle} formatter={(v) => fmt(v)} />
            </PieChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 mb-3">
        {/* Referral Performance */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">🔗 Referral Performance</h3>
          {referralPerf.length === 0 ? <p className="text-t2 text-xs">No referrals yet</p> : (
            referralPerf.map((r, i) => (
              <div key={i} className="flex justify-between py-1.5 border-b border-bd text-xs">
                <span className="font-semibold">{r.name}</span>
                <div className="flex gap-3 text-right">
                  <span className="text-ac">{r.referrals} referrals</span>
                  <span className="text-pr font-bold">{fmt(r.bonus)} earned</span>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Payment Methods */}
        <div className="bg-s1 border border-bd rounded-[10px] p-4">
          <h3 className="text-[13px] font-bold mb-3">💳 Payment Methods</h3>
          {payPie.length > 0 ? (
            <ResponsiveContainer width="100%" height={200}>
              <PieChart>
                <Pie data={payPie} cx="50%" cy="50%" outerRadius={70} dataKey="value" label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}>
                  {payPie.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                </Pie>
                <Tooltip {...tooltipStyle} formatter={(v) => fmt(v)} />
              </PieChart>
            </ResponsiveContainer>
          ) : <p className="text-t2 text-xs">No data</p>}
        </div>
      </div>
    </div>
  );
}
