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'];

interface OverviewData {
  total_clicks: number;
  total_conversions: number;
  total_revenue: number;
  total_pageviews: number;
  ctr: string;
  total_watchlist: number;
  active_price_watches: number;
}

interface TopProduct {
  product_id: string;
  product_name: string | null;
  slug: string | null;
  total_clicks: string;
  total_conversions: string;
  total_revenue: string;
  pageviews: number;
  ctr: string;
}

interface SourceData {
  source: string;
  total_clicks: string;
}

interface TimeseriesRow {
  date: string;
  clicks: number;
  conversions: number;
  revenue: number;
}

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<TimeseriesRow[]>([]);
  const [overview, setOverview] = useState<OverviewData | null>(null);
  const [topProducts, setTopProducts] = useState<TopProduct[]>([]);
  const [sources, setSources] = useState<SourceData[]>([]);
  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 totalPageviews = Number(overview?.total_pageviews || 0);
  const ctr = overview?.ctr || '0';
  const totalWatchlist = Number(overview?.total_watchlist || 0);
  const activePriceWatches = Number(overview?.active_price_watches || 0);

  const sourceData = sources.map(s => ({
    name: s.source || 'Unknown',
    value: Number(s.total_clicks || 0),
  })).filter(s => 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-4">
        <StatCard label="Pageviews" value={totalPageviews.toLocaleString()} />
        <StatCard label="Clicks" value={totalClicks.toLocaleString()} />
        <StatCard label="Conversions" value={totalConversions.toLocaleString()} />
        <StatCard label="Revenue" value={`€${totalRevenue.toFixed(2)}`} />
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-8">
        <StatCard label="CTR (clicks/views)" value={`${ctr}%`} />
        <StatCard label="Watchlist adds" value={totalWatchlist.toLocaleString()} />
        <StatCard label="Actieve price watches" value={activePriceWatches.toLocaleString()} />
        <StatCard label="Conv. rate" value={totalClicks > 0 ? `${((totalConversions / totalClicks) * 100).toFixed(2)}%` : '0%'} />
      </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, i) => {
                const clicks = Number(p.total_clicks);
                const revenue = Number(p.total_revenue || 0);
                const displayName = p.product_name || p.product_id;

                return (
                  <div key={i} className="flex items-center justify-between">
                    <div className="flex items-center gap-3 min-w-0">
                      <span className="text-xs text-[#666] w-4 shrink-0">{i + 1}.</span>
                      {p.slug ? (
                        <a href={`/sneaker/${p.slug}`} className="text-sm text-[#F5F5F5] truncate max-w-[200px] hover:text-[#00FF6A] transition-colors" title={displayName}>
                          {displayName}
                        </a>
                      ) : (
                        <span className="text-sm text-[#F5F5F5] truncate max-w-[200px]">{displayName}</span>
                      )}
                    </div>
                    <div className="flex gap-3 text-xs shrink-0">
                      <span className="text-[#666]">{p.pageviews} views</span>
                      <span className="text-[#999]">{clicks.toLocaleString()} clicks</span>
                      <span className="text-[#06B6D4]">{p.ctr}% CTR</span>
                      <span className="text-[#00FF6A]">€{revenue.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((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>
              <div className="space-y-2">
                {sourceData.map((s, i) => (
                  <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>;
}
