import React, { useState, useEffect } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';

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 EmailStatsContent() {
  const { token } = useAuth();
  const [overview, setOverview] = useState<any>(null);
  const [recent, setRecent] = useState<any[]>([]);
  const [mostWatched, setMostWatched] = useState<any[]>([]);
  const [tab, setTab] = useState<'overview' | 'recent' | 'watchlist'>('overview');
  const [loading, setLoading] = useState(true);

  const headers = { Authorization: `Bearer ${token}` };

  useEffect(() => {
    Promise.all([
      fetch('/api/admin/emails?view=overview', { headers }).then(r => r.json()),
      fetch('/api/admin/emails?view=recent', { headers }).then(r => r.json()),
      fetch('/api/admin/emails?view=most-watched', { headers }).then(r => r.json()),
    ]).then(([ov, rec, mw]) => {
      setOverview(ov);
      setRecent(rec.data || []);
      setMostWatched(mw.data || []);
    }).finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <AdminLayout title="Email & Watchlist">
      <div className="flex items-center justify-center py-20">
        <div className="w-8 h-8 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
      </div>
    </AdminLayout>
  );

  const emails = overview?.emails || {};
  const wl = overview?.watchlist || {};

  return (
    <AdminLayout title="Email & Watchlist">
      {/* Sub-nav */}
      <div className="flex gap-4 mb-6 border-b border-[#333] pb-3">
        {(['overview', 'recent', 'watchlist'] as const).map(t => (
          <button key={t} onClick={() => setTab(t)}
            className={`text-sm pb-1 ${tab === t ? 'text-[#00FF6A] border-b-2 border-[#00FF6A]' : 'text-[#999] hover:text-white'}`}>
            {t === 'overview' ? 'Overzicht' : t === 'recent' ? 'Recent' : 'Watchlist'}
          </button>
        ))}
        <a href="/admin/emails/editor" className="ml-auto text-sm text-[#00FF6A] hover:underline">✏️ Email Editor</a>
      </div>

      {tab === 'overview' && (
        <>
          <h3 className="text-[#999] text-sm font-medium mb-3 uppercase tracking-wider">Email Stats</h3>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
            <StatCard label="Totaal Verstuurd" value={emails.total_sent || 0} icon="📧" />
            <StatCard label="Unieke Gebruikers" value={emails.unique_users || 0} icon="👤" />
            <StatCard label="Prijsalerts" value={emails.price_alerts || 0} icon="🔔" />
            <StatCard label="Weekly Digests" value={emails.weekly_digests || 0} icon="📰" />
            <StatCard label="Verificaties" value={emails.verifications || 0} icon="✅" />
          </div>

          <h3 className="text-[#999] text-sm font-medium mb-3 uppercase tracking-wider">Watchlist Stats</h3>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            <StatCard label="Totaal Items" value={wl.total_items || 0} icon="👀" />
            <StatCard label="Unieke Gebruikers" value={wl.unique_users || 0} icon="👤" />
            <StatCard label="Gem. per Gebruiker" value={wl.avg_per_user || 0} icon="📊" />
          </div>
        </>
      )}

      {tab === 'recent' && (
        <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
          {recent.length === 0 ? (
            <div className="text-[#666] text-center py-20">Geen emails verstuurd</div>
          ) : (
            <table className="w-full text-sm">
              <thead className="text-[#999] text-left bg-[#0F0F0F]">
                <tr><th className="p-3">Datum</th><th className="p-3">Type</th><th className="p-3">Email</th><th className="p-3">Product</th><th className="p-3">Resend ID</th></tr>
              </thead>
              <tbody>
                {recent.map((r: any, i: number) => (
                  <tr key={i} className="border-t border-[#222]">
                    <td className="p-3 text-[#999]">{new Date(r.created_at).toLocaleString('nl-NL')}</td>
                    <td className="p-3"><span className="bg-[#1A1A1A] text-[#F5F5F5] px-2 py-0.5 rounded text-xs">{r.email_type}</span></td>
                    <td className="p-3 text-[#F5F5F5]">{r.email || '-'}</td>
                    <td className="p-3 text-[#999] max-w-[200px] truncate">{r.product_name || '-'}</td>
                    <td className="p-3 text-[#666] text-xs font-mono">{r.resend_id || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {tab === 'watchlist' && (
        <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
          <h3 className="text-[#F5F5F5] font-semibold p-4 border-b border-[#222]">Meest Gevolgde Producten</h3>
          {mostWatched.length === 0 ? (
            <div className="text-[#666] text-center py-20">Geen watchlist data</div>
          ) : (
            <div className="divide-y divide-[#222]">
              {mostWatched.map((p: any, i: number) => (
                <div key={i} className="flex items-center gap-4 p-4">
                  <span className="text-[#666] w-6 text-right">{i + 1}</span>
                  {p.image_url && <img src={p.image_url} alt="" className="w-10 h-10 rounded bg-white object-contain" />}
                  <div className="flex-1 min-w-0">
                    <div className="text-[#F5F5F5] text-sm truncate">{p.name}</div>
                    <div className="text-xs text-[#666]">{p.brand}</div>
                  </div>
                  <span className="text-[#00FF6A] font-medium">{p.watchers} 👀</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </AdminLayout>
  );
}

export default function EmailStats() {
  return <AuthProvider><AuthGuard><EmailStatsContent /></AuthGuard></AuthProvider>;
}
