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

function FeedHealthContent() {
  const { token } = useAuth();
  const [feeds, setFeeds] = useState<any[]>([]);
  const [selectedFeed, setSelectedFeed] = useState<number | null>(null);
  const [history, setHistory] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    fetch('/api/admin/feeds/health', { headers })
      .then(r => r.json())
      .then(res => setFeeds(res.feeds || []))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (!selectedFeed) return;
    fetch(`/api/admin/feeds/health?feed_id=${selectedFeed}`, { headers })
      .then(r => r.json())
      .then(res => setHistory(res.history || []));
  }, [selectedFeed]);

  const formatDuration = (d: any) => {
    if (!d) return '-';
    const m = d.minutes || 0; const s = d.seconds || 0;
    return m > 0 ? `${m}m ${s}s` : `${s}s`;
  };

  const timeAgo = (dt: string) => {
    if (!dt) return 'Nooit';
    const diff = Date.now() - new Date(dt).getTime();
    const h = Math.floor(diff / 3600000);
    if (h < 1) return `${Math.floor(diff / 60000)}m geleden`;
    if (h < 24) return `${h}u geleden`;
    return `${Math.floor(h / 24)}d geleden`;
  };

  if (loading) return (
    <AdminLayout title="Feed Health">
      <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>
  );

  return (
    <AdminLayout title="Feed Health">
      <div className="space-y-4">
        {feeds.map((f: any) => (
          <div key={f.id} className={`bg-[#141414] border rounded-xl p-5 cursor-pointer transition-colors
            ${f.stale ? 'border-[#FF3B3B]/50' : f.high_errors ? 'border-[#FFD700]/50' : 'border-[#333]'}
            ${selectedFeed === f.id ? 'ring-1 ring-[#00FF6A]' : ''}`}
            onClick={() => setSelectedFeed(selectedFeed === f.id ? null : f.id)}>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <span className={`w-2 h-2 rounded-full ${f.is_enabled ? (f.stale ? 'bg-[#FF3B3B]' : 'bg-[#00FF6A]') : 'bg-[#666]'}`} />
                <span className="text-[#F5F5F5] font-medium">{f.name}</span>
                {f.stale && <span className="text-xs bg-[#FF3B3B]/20 text-[#FF3B3B] px-2 py-0.5 rounded">Stale (&gt;24h)</span>}
                {f.high_errors && <span className="text-xs bg-[#FFD700]/20 text-[#FFD700] px-2 py-0.5 rounded">High Errors</span>}
              </div>
              <div className="flex items-center gap-6 text-sm text-[#999]">
                <span title="Products">{f.product_count || 0} prod.</span>
                <span title="Sneaker ratio">{f.sneaker_ratio}% sneakers</span>
                <span title="Last sync">{timeAgo(f.last_sync_at)}</span>
                <span title="Duration">{formatDuration(f.duration)}</span>
                <span className={f.last_sync_status === 'success' ? 'text-[#00FF6A]' : 'text-[#FF3B3B]'}>
                  {f.last_sync_status || '-'}
                </span>
              </div>
            </div>

            {/* Expanded details */}
            {selectedFeed === f.id && (
              <div className="mt-4 pt-4 border-t border-[#222]">
                <div className="grid grid-cols-5 gap-4 text-sm mb-4">
                  <div><span className="text-[#666]">Fetched:</span> <span className="text-[#F5F5F5]">{f.products_fetched ?? '-'}</span></div>
                  <div><span className="text-[#666]">New:</span> <span className="text-[#00FF6A]">{f.products_new ?? '-'}</span></div>
                  <div><span className="text-[#666]">Updated:</span> <span className="text-[#F5F5F5]">{f.products_updated ?? '-'}</span></div>
                  <div><span className="text-[#666]">Removed:</span> <span className="text-[#FF3B3B]">{f.products_removed ?? '-'}</span></div>
                  <div><span className="text-[#666]">Errors:</span> <span className={f.errors_count > 0 ? 'text-[#FFD700]' : 'text-[#F5F5F5]'}>{f.errors_count ?? '-'}</span></div>
                </div>
                {f.last_error && (
                  <div className="text-xs text-[#FF3B3B] bg-[#FF3B3B]/10 p-2 rounded mb-4 max-h-20 overflow-auto">{f.last_error}</div>
                )}

                {history.length > 0 && (
                  <div>
                    <h4 className="text-sm text-[#999] mb-2">Sync History</h4>
                    <ResponsiveContainer width="100%" height={150}>
                      <BarChart data={[...history].reverse()}>
                        <XAxis dataKey="started_at" tick={false} />
                        <YAxis tick={{ fill: '#999', fontSize: 11 }} />
                        <Tooltip contentStyle={{ background: '#1A1A1A', border: '1px solid #333', borderRadius: 8, fontSize: 12 }} />
                        <Bar dataKey="products_new" stackId="a" fill="#00FF6A" name="New" />
                        <Bar dataKey="products_updated" stackId="a" fill="#FFD700" name="Updated" />
                        <Bar dataKey="products_removed" stackId="a" fill="#FF3B3B" name="Removed" />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                )}
              </div>
            )}
          </div>
        ))}

        {feeds.length === 0 && (
          <div className="text-[#666] text-center py-20">Geen feeds geconfigureerd</div>
        )}
      </div>
    </AdminLayout>
  );
}

export default function FeedHealth() {
  return <AuthProvider><AuthGuard><FeedHealthContent /></AuthGuard></AuthProvider>;
}
