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

function CronContent() {
  const { token } = useAuth();
  const [crons, setCrons] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [triggering, setTriggering] = useState<string | null>(null);

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

  const load = () => {
    fetch('/api/admin/crons', { headers })
      .then(r => r.json())
      .then(res => setCrons(res.crons || []))
      .finally(() => setLoading(false));
  };

  useEffect(load, []);

  const trigger = async (name: string) => {
    setTriggering(name);
    await fetch('/api/admin/crons', {
      method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' },
      body: JSON.stringify({ name }),
    });
    setTimeout(() => { load(); setTriggering(null); }, 1000);
  };

  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="Cron Jobs">
      <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="Cron Jobs">
      <div className="space-y-3">
        {crons.map((c: any) => {
          const lr = c.last_run;
          const statusColor = !lr ? 'text-[#666]' : lr.status === 'ok' ? 'text-[#00FF6A]' : lr.status === 'error' ? 'text-[#FF3B3B]' : 'text-[#FFD700]';
          return (
            <div key={c.name} className="bg-[#141414] border border-[#333] rounded-xl p-5">
              <div className="flex items-center justify-between">
                <div>
                  <div className="flex items-center gap-3">
                    <span className={`w-2 h-2 rounded-full ${!lr ? 'bg-[#666]' : lr.status === 'ok' ? 'bg-[#00FF6A]' : lr.status === 'error' ? 'bg-[#FF3B3B]' : 'bg-[#FFD700]'}`} />
                    <span className="text-[#F5F5F5] font-medium">{c.name}</span>
                    <span className="text-xs text-[#666]">{c.description}</span>
                  </div>
                  <div className="flex items-center gap-6 mt-2 text-sm text-[#999]">
                    <span>📅 {c.schedule}</span>
                    <span>🕐 {lr ? timeAgo(lr.started_at) : 'Nooit gedraaid'}</span>
                    {lr?.duration_secs != null && <span>⏱️ {Math.round(lr.duration_secs)}s</span>}
                    <span className={statusColor}>{lr?.status || 'unknown'}</span>
                  </div>
                </div>
                <button onClick={() => trigger(c.name)} disabled={triggering === c.name}
                  className="px-4 py-2 rounded-lg text-sm bg-[#1A1A1A] border border-[#333] text-[#999] hover:text-[#00FF6A] hover:border-[#00FF6A] transition-colors disabled:opacity-50">
                  {triggering === c.name ? '⏳' : '▶️'} Run
                </button>
              </div>
              {lr?.output_summary && (
                <div className="mt-3 text-xs text-[#666] bg-[#0A0A0A] p-2 rounded">{lr.output_summary}</div>
              )}
              {lr?.error_message && (
                <div className="mt-3 text-xs text-[#FF3B3B] bg-[#FF3B3B]/10 p-2 rounded">{lr.error_message}</div>
              )}
            </div>
          );
        })}
      </div>
    </AdminLayout>
  );
}

export default function CronMonitor() {
  return <AuthProvider><AuthGuard><CronContent /></AuthGuard></AuthProvider>;
}
