import React, { useState, useEffect } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, BarChart, Bar, 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');

  // Mock data
  const timeseries = Array.from({ length: days }, (_, i) => ({
    date: new Date(Date.now() - (days - 1 - i) * 86400000).toISOString().slice(0, 10),
    clicks: Math.floor(Math.random() * 300 + 100),
    revenue: Math.floor(Math.random() * 150 + 20),
    conversions: Math.floor(Math.random() * 15 + 1),
  }));

  const totalClicks = timeseries.reduce((s, d) => s + d.clicks, 0);
  const totalRevenue = timeseries.reduce((s, d) => s + d.revenue, 0);
  const totalConversions = timeseries.reduce((s, d) => s + d.conversions, 0);
  const ctr = totalClicks > 0 ? (totalConversions / totalClicks * 100).toFixed(2) : '0';
  const roas = (totalRevenue / Math.max(totalClicks * 0.15, 1)).toFixed(2);

  const topProducts = [
    { name: 'Nike Dunk Low Panda', clicks: 342, revenue: 89 },
    { name: 'NB 550 White Grey', clicks: 234, revenue: 67 },
    { name: 'Adidas Samba OG', clicks: 198, revenue: 54 },
    { name: 'Nike Air Max 90', clicks: 167, revenue: 43 },
    { name: 'Asics Gel-1130', clicks: 134, revenue: 38 },
  ];

  const topShops = [
    { name: 'Footlocker', revenue: 124 },
    { name: 'JD Sports', revenue: 98 },
    { name: 'Zalando', revenue: 76 },
    { name: 'Sneakerstad', revenue: 54 },
  ];

  const sources = [
    { name: 'Homepage', value: 42 },
    { name: 'Search', value: 31 },
    { name: 'Deals', value: 18 },
    { name: 'Google', value: 9 },
  ];

  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-5 gap-3 mb-8">
        <StatCard label="Clicks" value={totalClicks.toLocaleString()} />
        <StatCard label="Conversions" value={totalConversions.toString()} />
        <StatCard label="Revenue" value={`€${totalRevenue}`} />
        <StatCard label="CTR" value={`${ctr}%`} />
        <StatCard label="ROAS" value={`€${roas}`} />
      </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">
        <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
          <h3 className="text-sm font-medium text-[#999] mb-4">Top Products</h3>
          <div className="space-y-3">
            {topProducts.map((p, i) => (
              <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]">{p.name}</span>
                </div>
                <div className="flex gap-4 text-xs">
                  <span className="text-[#999]">{p.clicks} clicks</span>
                  <span className="text-[#00FF6A]">€{p.revenue}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
          <h3 className="text-sm font-medium text-[#999] mb-4">Top Shops by Revenue</h3>
          <div className="space-y-3">
            {topShops.map((s, i) => (
              <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]">{s.name}</span>
                </div>
                <span className="text-sm text-[#00FF6A]">€{s.revenue}</span>
              </div>
            ))}
          </div>
        </div>

        <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={sources} dataKey="value" cx="50%" cy="50%" innerRadius={25} outerRadius={50}>
                    {sources.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="space-y-2">
              {sources.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] }} />
                  <span className="text-[#999]">{s.name}</span>
                  <span className="text-[#F5F5F5]">{s.value}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="bg-[#141414] border border-[#333] rounded-xl p-5">
          <h3 className="text-sm font-medium text-[#999] mb-4">Revenue by Network</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-[#F5F5F5]">Webgains</span>
              <div className="flex items-center gap-2">
                <span className="text-sm text-[#00FF6A]">€210</span>
                <span className="text-xs text-[#999]">(61%)</span>
              </div>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-[#F5F5F5]">TradeTracker</span>
              <div className="flex items-center gap-2">
                <span className="text-sm text-[#00FF6A]">€132</span>
                <span className="text-xs text-[#999]">(39%)</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}

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