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

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

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-[#141414] border border-[#333] rounded-xl p-4 text-center">
      <div className="text-xl font-bold text-[#F5F5F5]">{value}</div>
      <div className="text-xs text-[#999] mt-1">{label}</div>
    </div>
  );
}

function AnalyticsContent() {
  const { token } = useAuth();
  const [days, setDays] = useState(30);
  const [tab, setTab] = useState<'clicks' | 'revenue' | 'conversions'>('clicks');
  const [timeseries, setTimeseries] = useState<any[]>([]);
  const [overview, setOverview] = useState<any>(null);
  const [topProducts, setTopProducts] = useState<any[]>([]);
  const [sources, setSources] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const h = { Authorization: `Bearer ${token}` };
    setLoading(true);
    Promise.all([
      fetch(`/api/admin/analytics?type=timeseries&days=${days}`, { headers: h }).then(r => r.json()),
      fetch(`/api/admin/analytics?type=overview&days=${days}`, { headers: h }).then(r => r.json()),
      fetch(`/api/admin/analytics?type=top-products&days=${days}`, { headers: h }).then(r => r.json()),
      fetch(`/api/admin/analytics?type=sources&days=${days}`, { headers: h }).then(r => r.json()),
    ]).then(([ts, ov, tp, src]) => {
      setTimeseries(ts.data || []);
      setOverview(ov);
      setTopProducts(tp.data || []);
      setSources(src.data || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, [token, days]);

  const hasData = timeseries.length > 0;

  if (loading) return <AdminLayout title="Analytics"><div className="text-[#666] text-center py-12">Laden...</div></AdminLayout>;

  if (!hasData) {
    return (
      <AdminLayout title="Analytics">
        <div className="bg-[#141414] border border-[#333] rounded-xl p-12 text-center">
          <div className="text-4xl mb-4">📊</div>
          <div className="text-[#999] text-lg mb-2">Begin met adverteren om analytics te zien</div>
          <div className="text-[#666] text-sm">Zodra er clicks en conversies binnenkomen verschijnt hier je data</div>
        </div>
      </AdminLayout>
    );
  }

  const totalClicks = Number(overview?.total_clicks || 0);
  const totalConversions = Number(overview?.total_conversions || 0);
  const totalRevenue = Number(overview?.total_revenue || 0);
  const ctr = Number(overview?.ctr || 0);

  const sourceData = sources.map((s: any) => ({
    name: s.source || 'Unknown',
    value: Number(s.total_clicks || 0),
  })).filter((s: any) => s.value > 0);

  return (
    <AdminLayout title="Analytics">
      <div className="flex gap-2 mb-6">
        {[7, 14, 30, 90].map(d => (
          <button key={d} onClick={() => setDays(d)}
            className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${days === d ? 'bg-[#00FF6A]/10 text-[#00FF6A] border border-[#00FF6A]/30' : 'bg-[#141414] border border-[#333] text-[#999] hover:text-[#F5F5F5]'}`}>
            {d}d
          </button>
        ))}
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-8">
        <StatCard label="Clicks" value={totalClicks.toLocaleString()} />
        <StatCard label="Conversions" value={totalConversions.toLocaleString()} />
        <StatCard label="Revenue" value={`€${totalRevenue.toFixed(2)}`} />
        <StatCard label="CTR" value={`${ctr}%`} />
      </div>

      <div className="flex gap-2 mb-4">
        {(['clicks', 'revenue', 'conversions'] as const).map(t => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-3 py-1.5 rounded-lg text-sm capitalize ${tab === t ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : 'text-[#999] hover:text-[#F5F5F5]'}`}>
            {t}
          </button>
        ))}
      </div>

      <div className="bg-[#141414] border border-[#333] rounded-xl p-5 mb-8">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={timeseries}>
            <XAxis dataKey="date" tick={{ fill: '#666', fontSize: 10 }} tickFormatter={v => v.slice(5)} />
            <YAxis tick={{ fill: '#666', fontSize: 10 }} />
            <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8, color: '#F5F5F5' }} />
            <Bar dataKey={tab} fill="#00FF6A" radius={[2, 2, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {topProducts.length > 0 && (
          <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
            <h3 className="text-sm font-medium text-[#999] mb-4">Top Producten</h3>
            <div className="space-y-3">
              {topProducts.slice(0, 10).map((p: any, i: number) => (
                <div key={i} className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span className="text-xs text-[#666] w-4">{i + 1}.</span>
                    <span className="text-sm text-[#F5F5F5] truncate max-w-[200px]">{p.product_id}</span>
                  </div>
                  <div className="flex gap-4 text-xs">
                    <span className="text-[#999]">{Number(p.total_clicks).toLocaleString()} clicks</span>
                    <span className="text-[#00FF6A]">€{Number(p.total_revenue || 0).toFixed(2)}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {sourceData.length > 0 && (
          <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
            <h3 className="text-sm font-medium text-[#999] mb-4">Traffic Sources</h3>
            <div className="flex items-center gap-6">
              <div className="w-32 h-32">
                <ResponsiveContainer>
                  <PieChart>
                    <Pie data={sourceData} dataKey="value" cx="50%" cy="50%" innerRadius={25} outerRadius={50}>
                      {sourceData.map((_: any, i: number) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>
              <div className="space-y-2">
                {sourceData.map((s: any, i: number) => (
                  <div key={i} className="flex items-center gap-2 text-sm">
                    <div className="w-3 h-3 rounded-full" style={{ background: COLORS[i % COLORS.length] }} />
                    <span className="text-[#999]">{s.name}</span>
                    <span className="text-[#F5F5F5]">{s.value}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}

export default function AnalyticsPage() {
  return <AuthProvider><AuthGuard><AnalyticsContent /></AuthGuard></AuthProvider>;
}
