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

interface Stats {
  total_sneakers: number;
  total_products: number;
  active_feeds: number;
  clicks_today: number;
  revenue_month: number;
  last_sync_at: string | null;
}

function StatCard({ label, value, icon, sub }: { label: string; value: string | number; icon: string; sub?: 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>
      {sub && <div className="text-xs text-[#666] mt-1">{sub}</div>}
    </div>
  );
}

function DashboardContent() {
  const { token } = useAuth();
  const [stats, setStats] = useState<Stats | null>(null);
  const [timeseries, setTimeseries] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const headers = { Authorization: `Bearer ${token}` };
    Promise.all([
      fetch('/api/admin/stats', { headers }).then(r => r.json()),
      fetch('/api/admin/analytics?type=timeseries&days=30', { headers }).then(r => r.json()),
    ]).then(([s, ts]) => {
      setStats(s);
      setTimeseries(ts.data || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, [token]);

  if (loading) {
    return (
      <AdminLayout title="Dashboard">
        <div className="flex items-center justify-center h-64 text-[#666]">Laden...</div>
      </AdminLayout>
    );
  }

  const formatSync = (iso: string | null) => {
    if (!iso) return 'Nooit';
    const d = new Date(iso);
    const mins = Math.floor((Date.now() - d.getTime()) / 60000);
    if (mins < 1) return 'Zojuist';
    if (mins < 60) return `${mins} min geleden`;
    if (mins < 1440) return `${Math.floor(mins / 60)} uur geleden`;
    return `${Math.floor(mins / 1440)} dagen geleden`;
  };

  return (
    <AdminLayout title="Dashboard">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4 mb-8">
        <StatCard label="Sneakers" value={Number(stats?.total_sneakers || 0).toLocaleString()} icon="👟" />
        <StatCard label="Totaal producten" value={Number(stats?.total_products || 0).toLocaleString()} icon="📦" />
        <StatCard label="Actieve feeds" value={Number(stats?.active_feeds || 0)} icon="📡" />
        <StatCard label="Clicks vandaag" value={Number(stats?.clicks_today || 0).toLocaleString()} icon="🖱️" />
        <StatCard label="Revenue (maand)" value={`€${Number(stats?.revenue_month || 0).toFixed(2)}`} icon="💰" />
        <StatCard label="Laatste sync" value={formatSync(stats?.last_sync_at || null)} icon="🔄" />
      </div>

      {timeseries.length === 0 ? (
        <div className="bg-[#141414] border border-[#333] rounded-xl p-8 text-center">
          <div className="text-[#666] text-lg mb-2">📊</div>
          <div className="text-[#999] text-sm">Nog geen analytics data</div>
          <div className="text-[#666] text-xs mt-1">Data verschijnt hier zodra er clicks en conversies binnenkomen</div>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
            <h3 className="text-sm font-medium text-[#999] mb-4">Clicks (30 dagen)</h3>
            <ResponsiveContainer width="100%" height={200}>
              <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 }} labelStyle={{ color: '#999' }} />
                <Bar dataKey="clicks" fill="#00FF6A" radius={[2, 2, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>

          <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
            <h3 className="text-sm font-medium text-[#999] mb-4">Revenue (30 dagen)</h3>
            <ResponsiveContainer width="100%" height={200}>
              <LineChart 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 }} labelStyle={{ color: '#999' }} />
                <Line type="monotone" dataKey="revenue" stroke="#00FF6A" strokeWidth={2} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}

export default function Dashboard() {
  return (
    <AuthProvider>
      <AuthGuard>
        <DashboardContent />
      </AuthGuard>
    </AuthProvider>
  );
}
