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

interface Feed {
  id: number;
  name: string;
  merchant_name: string | null;
  is_enabled: boolean;
  product_count: number;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_error: string | null;
  sync_frequency: string;
  provider_name: string;
  provider_slug: string;
}

interface SyncLog {
  id: number;
  status: string;
  started_at: string;
  finished_at: string | null;
  products_processed: number;
  products_created: number;
  products_updated: number;
  error_message: string | null;
}

function StatusBadge({ status }: { status: string | null }) {
  const s = status || 'unknown';
  const styles: Record<string, string> = {
    success: 'bg-[#00FF6A]/10 text-[#00FF6A]',
    failed: 'bg-[#FF3B3B]/10 text-[#FF3B3B]',
    running: 'bg-[#FFD700]/10 text-[#FFD700]',
    unknown: 'bg-[#666]/10 text-[#666]',
  };
  return <span className={`text-xs px-2 py-1 rounded-full ${styles[s] || styles.unknown}`}>{s}</span>;
}

function timeAgo(iso: string | null): string {
  if (!iso) return 'Nooit';
  const mins = Math.floor((Date.now() - new Date(iso).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`;
}

function FeedManagerContent() {
  const { token } = useAuth();
  const [feeds, setFeeds] = useState<Feed[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState<Set<number>>(new Set());
  const [logsFor, setLogsFor] = useState<number | null>(null);
  const [logs, setLogs] = useState<SyncLog[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);

  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };

  const loadFeeds = () => {
    fetch('/api/admin/feeds', { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.json())
      .then(d => setFeeds(d.feeds || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  useEffect(() => { loadFeeds(); }, [token]);

  const toggleFeed = async (feed: Feed) => {
    await fetch(`/api/admin/feeds/${feed.id}`, {
      method: 'PUT', headers,
      body: JSON.stringify({ is_enabled: !feed.is_enabled }),
    });
    setFeeds(prev => prev.map(f => f.id === feed.id ? { ...f, is_enabled: !f.is_enabled } : f));
  };

  const syncFeed = async (id: number) => {
    setSyncing(prev => new Set(prev).add(id));
    try {
      await fetch(`/api/admin/feeds/${id}/sync`, { method: 'POST', headers });
      loadFeeds();
    } catch {}
    setSyncing(prev => { const n = new Set(prev); n.delete(id); return n; });
  };

  const showLogs = async (id: number) => {
    if (logsFor === id) { setLogsFor(null); return; }
    setLogsFor(id);
    setLogsLoading(true);
    try {
      const res = await fetch(`/api/admin/feeds/${id}/logs?limit=10`, { headers: { Authorization: `Bearer ${token}` } });
      const d = await res.json();
      setLogs(d.logs || []);
    } catch { setLogs([]); }
    setLogsLoading(false);
  };

  if (loading) return <AdminLayout title="Feeds"><div className="text-[#666] text-center py-12">Laden...</div></AdminLayout>;

  return (
    <AdminLayout title="Feeds">
      {feeds.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">Geen feeds gevonden</div>
          <div className="text-[#666] text-xs mt-1">Feeds worden aangemaakt via de sync engine</div>
        </div>
      ) : (
        <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#333] text-[#999] text-left">
                <th className="px-5 py-3 font-medium">Feed</th>
                <th className="px-5 py-3 font-medium">Provider</th>
                <th className="px-5 py-3 font-medium">Status</th>
                <th className="px-5 py-3 font-medium">Producten</th>
                <th className="px-5 py-3 font-medium">Laatste sync</th>
                <th className="px-5 py-3 font-medium">Acties</th>
              </tr>
            </thead>
            <tbody>
              {feeds.map(feed => (
                <React.Fragment key={feed.id}>
                  <tr className="border-b border-[#222] hover:bg-[#1A1A1A] transition-colors">
                    <td className="px-5 py-3">
                      <div className="text-[#F5F5F5] font-medium">{feed.name}</div>
                      {feed.merchant_name && <div className="text-xs text-[#666]">{feed.merchant_name}</div>}
                    </td>
                    <td className="px-5 py-3 text-[#999]">{feed.provider_name}</td>
                    <td className="px-5 py-3">
                      <StatusBadge status={feed.is_enabled ? (feed.last_sync_status || 'unknown') : 'disabled'} />
                      {feed.last_error && (
                        <div className="text-xs text-[#FF3B3B] mt-1 max-w-[200px] truncate" title={feed.last_error}>{feed.last_error}</div>
                      )}
                    </td>
                    <td className="px-5 py-3 text-[#999]">{feed.product_count.toLocaleString()}</td>
                    <td className="px-5 py-3 text-[#999]">{timeAgo(feed.last_sync_at)}</td>
                    <td className="px-5 py-3">
                      <div className="flex gap-2">
                        <button onClick={() => syncFeed(feed.id)} disabled={syncing.has(feed.id)}
                          title="Force sync" className="text-[#999] hover:text-[#00FF6A] transition-colors disabled:opacity-30">
                          {syncing.has(feed.id) ? '⏳' : '🔄'}
                        </button>
                        <button onClick={() => toggleFeed(feed)} title={feed.is_enabled ? 'Uitschakelen' : 'Inschakelen'}
                          className="text-[#999] hover:text-[#F5F5F5] transition-colors">
                          {feed.is_enabled ? '⏸' : '▶️'}
                        </button>
                        <button onClick={() => showLogs(feed.id)} title="Sync logs"
                          className={`transition-colors ${logsFor === feed.id ? 'text-[#00FF6A]' : 'text-[#999] hover:text-[#F5F5F5]'}`}>
                          📋
                        </button>
                      </div>
                    </td>
                  </tr>
                  {logsFor === feed.id && (
                    <tr>
                      <td colSpan={6} className="bg-[#0A0A0A] px-5 py-3">
                        {logsLoading ? (
                          <div className="text-[#666] text-xs">Laden...</div>
                        ) : logs.length === 0 ? (
                          <div className="text-[#666] text-xs">Geen sync logs</div>
                        ) : (
                          <table className="w-full text-xs">
                            <thead>
                              <tr className="text-[#666] text-left">
                                <th className="py-1 pr-4">Tijd</th>
                                <th className="py-1 pr-4">Status</th>
                                <th className="py-1 pr-4">Verwerkt</th>
                                <th className="py-1 pr-4">Nieuw</th>
                                <th className="py-1 pr-4">Updated</th>
                                <th className="py-1">Error</th>
                              </tr>
                            </thead>
                            <tbody>
                              {logs.map(log => (
                                <tr key={log.id} className="text-[#999]">
                                  <td className="py-1 pr-4">{new Date(log.started_at).toLocaleString('nl-NL')}</td>
                                  <td className="py-1 pr-4"><StatusBadge status={log.status} /></td>
                                  <td className="py-1 pr-4">{log.products_processed || 0}</td>
                                  <td className="py-1 pr-4">{log.products_created || 0}</td>
                                  <td className="py-1 pr-4">{log.products_updated || 0}</td>
                                  <td className="py-1 text-[#FF3B3B] max-w-[300px] truncate">{log.error_message || '-'}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        )}
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </AdminLayout>
  );
}

export default function FeedManagerPage() {
  return <AuthProvider><AuthGuard><FeedManagerContent /></AuthGuard></AuthProvider>;
}
