import React, { useState, useEffect } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';
import { LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, ComposedChart } from 'recharts';

const COLORS = ['#00FF6A', '#00CC55', '#FF6B35', '#FFD700', '#FF3B3B', '#6366F1', '#06B6D4'];

function StatCard({ label, value, icon }: { label: string; value: string | number; icon: string }) {
  return (
    <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
      <div className="flex items-center justify-between mb-2">
        <span className="text-[#999] text-sm">{label}</span>
        <span className="text-lg">{icon}</span>
      </div>
      <div className="text-2xl font-bold text-[#F5F5F5]">{value}</div>
    </div>
  );
}

function fmt(n: number) { return `€${Number(n).toFixed(2)}`; }

function RevenueContent() {
  const { token } = useAuth();
  const [days, setDays] = useState(30);
  const [overview, setOverview] = useState<any>(null);
  const [timeseries, setTimeseries] = useState<any[]>([]);
  const [byShop, setByShop] = useState<any[]>([]);
  const [byProduct, setByProduct] = useState<any[]>([]);
  const [bySource, setBySource] = useState<any[]>([]);
  const [byNetwork, setByNetwork] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const headers = { Authorization: `Bearer ${token}` };

  useEffect(() => {
    setLoading(true);
    Promise.all([
      fetch(`/api/admin/revenue?view=overview`, { headers }).then(r => r.json()),
      fetch(`/api/admin/revenue?view=timeseries&days=${days}`, { headers }).then(r => r.json()),
      fetch(`/api/admin/revenue?view=by-shop&days=${days}`, { headers }).then(r => r.json()),
      fetch(`/api/admin/revenue?view=by-product&days=${days}`, { headers }).then(r => r.json()),
      fetch(`/api/admin/revenue?view=by-source&days=${days}`, { headers }).then(r => r.json()),
      fetch(`/api/admin/revenue?view=by-network&days=${days}`, { headers }).then(r => r.json()),
    ]).then(([ov, ts, shop, prod, src, net]) => {
      setOverview(ov);
      setTimeseries(ts.data || []);
      setByShop(shop.data || []);
      setByProduct(prod.data || []);
      setBySource(src.data || []);
      setByNetwork(net.data || []);
    }).finally(() => setLoading(false));
  }, [days]);

  if (loading) return (
    <AdminLayout title="Revenue">
      <div className="flex items-center justify-center py-20">
        <div className="w-8 h-8 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
      </div>
    </AdminLayout>
  );

  return (
    <AdminLayout title="Revenue">
      {/* Period toggle */}
      <div className="flex gap-2 mb-6">
        {[30, 90].map(d => (
          <button key={d} onClick={() => setDays(d)}
            className={`px-4 py-1.5 rounded-lg text-sm ${days === d ? 'bg-[#00FF6A] text-black font-medium' : 'bg-[#1A1A1A] text-[#999] hover:text-white'}`}>
            {d} dagen
          </button>
        ))}
      </div>

      {/* Overview cards */}
      {overview && (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
          <StatCard label="Totale Revenue" value={fmt(overview.total_revenue)} icon="💰" />
          <StatCard label="Revenue (maand)" value={fmt(overview.revenue_month)} icon="📅" />
          <StatCard label="Revenue (vandaag)" value={fmt(overview.revenue_today)} icon="📈" />
          <StatCard label="Gem. Commissie" value={fmt(overview.avg_commission)} icon="💵" />
          <StatCard label="Conversies" value={overview.total_conversions} icon="🎯" />
          <StatCard label="Pending" value={fmt(overview.pending_revenue)} icon="⏳" />
        </div>
      )}

      {/* Revenue timeseries */}
      <div className="bg-[#141414] border border-[#333] rounded-xl p-6 mb-6">
        <h3 className="text-[#F5F5F5] font-semibold mb-4">Revenue & Conversies</h3>
        {timeseries.length === 0 ? (
          <div className="text-[#666] text-center py-12">Geen data beschikbaar</div>
        ) : (
          <ResponsiveContainer width="100%" height={300}>
            <ComposedChart data={timeseries}>
              <CartesianGrid strokeDasharray="3 3" stroke="#333" />
              <XAxis dataKey="date" tick={{ fill: '#999', fontSize: 12 }} />
              <YAxis yAxisId="left" tick={{ fill: '#999', fontSize: 12 }} />
              <YAxis yAxisId="right" orientation="right" tick={{ fill: '#999', fontSize: 12 }} />
              <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8 }} />
              <Line yAxisId="left" type="monotone" dataKey="revenue" stroke="#00FF6A" strokeWidth={2} dot={false} name="Revenue (€)" />
              <Bar yAxisId="right" dataKey="conversions" fill="#00FF6A" opacity={0.3} name="Conversies" />
            </ComposedChart>
          </ResponsiveContainer>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        {/* Revenue by shop */}
        <div className="bg-[#141414] border border-[#333] rounded-xl p-6">
          <h3 className="text-[#F5F5F5] font-semibold mb-4">Revenue per Shop</h3>
          {byShop.length === 0 ? (
            <div className="text-[#666] text-center py-12">Geen data</div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={byShop} layout="vertical">
                <XAxis type="number" tick={{ fill: '#999', fontSize: 12 }} />
                <YAxis type="category" dataKey="shop" tick={{ fill: '#999', fontSize: 11 }} width={120} />
                <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8 }} />
                <Bar dataKey="revenue" fill="#00FF6A" radius={[0, 4, 4, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Revenue by source */}
        <div className="bg-[#141414] border border-[#333] rounded-xl p-6">
          <h3 className="text-[#F5F5F5] font-semibold mb-4">Revenue per Bron</h3>
          {bySource.length === 0 ? (
            <div className="text-[#666] text-center py-12">Geen data</div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie data={bySource} dataKey="revenue" nameKey="source" cx="50%" cy="50%" outerRadius={100} label={({ source, percent }) => `${source} (${(percent * 100).toFixed(0)}%)`}>
                  {bySource.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                </Pie>
                <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8 }} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Revenue by product */}
        <div className="bg-[#141414] border border-[#333] rounded-xl p-6">
          <h3 className="text-[#F5F5F5] font-semibold mb-4">Top 20 Producten</h3>
          {byProduct.length === 0 ? (
            <div className="text-[#666] text-center py-12">Geen data</div>
          ) : (
            <div className="overflow-auto max-h-[400px]">
              <table className="w-full text-sm">
                <thead className="text-[#999] text-left sticky top-0 bg-[#141414]">
                  <tr><th className="pb-2">Product</th><th className="pb-2">Clicks</th><th className="pb-2">Conv.</th><th className="pb-2">Revenue</th><th className="pb-2">CR%</th></tr>
                </thead>
                <tbody>
                  {byProduct.map((p: any, i: number) => (
                    <tr key={i} className="border-t border-[#222]">
                      <td className="py-2 text-[#F5F5F5] max-w-[200px] truncate">{p.product}</td>
                      <td className="py-2 text-[#999]">{p.clicks}</td>
                      <td className="py-2 text-[#999]">{p.conversions}</td>
                      <td className="py-2 text-[#00FF6A]">{fmt(p.revenue)}</td>
                      <td className="py-2 text-[#999]">{p.cr}%</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Network breakdown */}
        <div className="bg-[#141414] border border-[#333] rounded-xl p-6">
          <h3 className="text-[#F5F5F5] font-semibold mb-4">Network Breakdown</h3>
          {byNetwork.length === 0 ? (
            <div className="text-[#666] text-center py-12">Geen data</div>
          ) : (
            <>
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie data={byNetwork} dataKey="revenue" nameKey="network" cx="50%" cy="50%" outerRadius={80} label={({ network }) => network}>
                    {byNetwork.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8 }} />
                </PieChart>
              </ResponsiveContainer>
              <div className="mt-4 space-y-2">
                {byNetwork.map((n: any, i: number) => (
                  <div key={i} className="flex justify-between text-sm">
                    <span className="text-[#F5F5F5]">{n.network || 'Unknown'}</span>
                    <span className="text-[#00FF6A]">{fmt(n.revenue)} ({n.conversions} conv.)</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </AdminLayout>
  );
}

export default function RevenueDashboard() {
  return <AuthProvider><AuthGuard><RevenueContent /></AuthGuard></AuthProvider>;
}
