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

function PerformanceContent() {
  const { token } = useAuth();
  const [days, setDays] = useState(30);
  const [brand, setBrand] = useState('');
  const [sort, setSort] = useState('score');
  const [order, setOrder] = useState<'desc' | 'asc'>('desc');
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    setLoading(true);
    const params = new URLSearchParams({ days: String(days), sort, order, page: String(page), limit: '50' });
    if (brand) params.set('brand', brand);
    fetch(`/api/admin/performance?${params}`, { headers })
      .then(r => r.json())
      .then(res => { setData(res.data || []); setTotal(res.total || 0); })
      .finally(() => setLoading(false));
  }, [days, brand, sort, order, page]);

  const toggleSort = (col: string) => {
    if (sort === col) setOrder(order === 'desc' ? 'asc' : 'desc');
    else { setSort(col); setOrder('desc'); }
  };

  const exportCSV = () => {
    const cols = ['name', 'brand', 'pageviews', 'clicks', 'watchlist_adds', 'active_alerts', 'ctr', 'conversions', 'revenue', 'score'];
    const csv = [cols.join(','), ...data.map(r => cols.map(c => `"${r[c] ?? ''}"`).join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `performance-${days}d.csv`; a.click();
  };

  const SortHeader = ({ col, label }: { col: string; label: string }) => (
    <th className="pb-2 cursor-pointer hover:text-[#00FF6A] select-none" onClick={() => toggleSort(col)}>
      {label} {sort === col && (order === 'desc' ? '↓' : '↑')}
    </th>
  );

  return (
    <AdminLayout title="Product Performance">
      <div className="flex flex-wrap gap-3 mb-6 items-center">
        {[7, 30, 90].map(d => (
          <button key={d} onClick={() => { setDays(d); setPage(1); }}
            className={`px-4 py-1.5 rounded-lg text-sm ${days === d ? 'bg-[#00FF6A] text-black font-medium' : 'bg-[#1A1A1A] text-[#999] hover:text-white'}`}>
            {d}d
          </button>
        ))}
        <input type="text" placeholder="Filter merk..." value={brand} onChange={e => { setBrand(e.target.value); setPage(1); }}
          className="bg-[#1A1A1A] border border-[#333] rounded-lg px-3 py-1.5 text-sm text-[#F5F5F5] w-48" />
        <button onClick={exportCSV} className="ml-auto px-4 py-1.5 rounded-lg text-sm bg-[#1A1A1A] text-[#999] hover:text-white border border-[#333]">
          📥 Export CSV
        </button>
      </div>

      <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
        {loading ? (
          <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>
        ) : data.length === 0 ? (
          <div className="text-[#666] text-center py-20">Geen producten gevonden</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="text-[#999] text-left bg-[#0F0F0F]">
                <tr>
                  <th className="p-3">Product</th>
                  <SortHeader col="pageviews" label="Views" />
                  <SortHeader col="clicks" label="Clicks" />
                  <SortHeader col="watchlist" label="Watchlist" />
                  <th className="pb-2">Alerts</th>
                  <SortHeader col="ctr" label="CTR" />
                  <SortHeader col="conversions" label="Conv." />
                  <SortHeader col="revenue" label="Revenue" />
                  <SortHeader col="score" label="Score" />
                </tr>
              </thead>
              <tbody>
                {data.map((r: any, i: number) => (
                  <tr key={i} className="border-t border-[#222] hover:bg-[#1A1A1A]">
                    <td className="p-3">
                      <div className="text-[#F5F5F5] max-w-[250px] truncate">{r.name}</div>
                      <div className="text-xs text-[#666]">{r.brand}</div>
                    </td>
                    <td className="p-3 text-[#999]">{r.pageviews}</td>
                    <td className="p-3 text-[#999]">{r.clicks}</td>
                    <td className="p-3 text-[#999]">{r.watchlist_adds}</td>
                    <td className="p-3 text-[#999]">{r.active_alerts}</td>
                    <td className="p-3 text-[#999]">{r.ctr}%</td>
                    <td className="p-3 text-[#999]">{r.conversions}</td>
                    <td className="p-3 text-[#00FF6A]">€{Number(r.revenue).toFixed(2)}</td>
                    <td className="p-3 font-medium text-[#F5F5F5]">{Math.round(Number(r.score))}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {/* Pagination */}
        <div className="flex items-center justify-between px-4 py-3 border-t border-[#222] text-sm text-[#999]">
          <span>{total} producten</span>
          <div className="flex gap-2">
            <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}
              className="px-3 py-1 rounded bg-[#1A1A1A] disabled:opacity-30">←</button>
            <span className="px-3 py-1">Pagina {page}</span>
            <button onClick={() => setPage(p => p + 1)} disabled={data.length < 50}
              className="px-3 py-1 rounded bg-[#1A1A1A] disabled:opacity-30">→</button>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}

export default function PerformanceDashboard() {
  return <AuthProvider><AuthGuard><PerformanceContent /></AuthGuard></AuthProvider>;
}
