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

interface Stats {
  total_products: number;
  active_feeds: number;
  clicks_today: number;
  revenue_month: number;
}

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 DashboardContent() {
  const { token } = useAuth();
  const [stats, setStats] = useState<Stats>({ total_products: 0, active_feeds: 0, clicks_today: 0, revenue_month: 0 });
  const [timeseries, setTimeseries] = useState<any[]>([]);

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

  // Generate mock data if no real data
  const chartData = timeseries.length > 0 ? timeseries :
    Array.from({ length: 30 }, (_, i) => ({
      date: new Date(Date.now() - (29 - i) * 86400000).toISOString().slice(0, 10),
      clicks: Math.floor(Math.random() * 200 + 50),
      revenue: Math.floor(Math.random() * 100 + 10),
      conversions: Math.floor(Math.random() * 10),
    }));

  return (
    <AdminLayout title="Dashboard">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard label="Total Products" value={stats.total_products.toLocaleString()} icon="P" />
        <StatCard label="Active Feeds" value={stats.active_feeds} icon="📡" />
        <StatCard label="Clicks Today" value={stats.clicks_today.toLocaleString()} icon="C" />
        <StatCard label="Revenue (month)" value={`€${Number(stats.revenue_month).toFixed(2)}`} icon="R" />
      </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 days)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={chartData}>
              <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 days)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={chartData}>
              <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>
  );
}
