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 [testAlert, setTestAlert] = useState<{ loading: boolean; result: string | null; error: boolean }>({ loading: false, result: null, error: false });

  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 sendTestAlert = async () => {
    setTestAlert({ loading: true, result: null, error: false });
    try {
      const res = await fetch('/api/admin/emails/send-test-alert', {
        method: 'POST',
        headers: { ...headers, 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });
      const data = await res.json();
      if (!res.ok) {
        setTestAlert({ loading: false, result: data.error || 'Verzenden mislukt', error: true });
      } else {
        setTestAlert({ loading: false, result: `Verstuurd naar ${data.sent_to}: ${data.product} (${data.lowest_price})`, error: false });
      }
    } catch (err: any) {
      setTestAlert({ loading: false, result: err.message, error: true });
    }
  };

  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="bg-[#141414] border border-[#333] rounded-xl p-5 mb-6">
        <div className="flex items-center justify-between">
          <div>
            <span className="text-[#F5F5F5] font-medium">Test prijsalert</span>
            <p className="text-xs text-[#999] mt-1">Stuurt een test prijsalert-email naar het admin adres met een willekeurig product</p>
          </div>
          <button onClick={sendTestAlert} disabled={testAlert.loading}
            className="px-4 py-2 rounded-lg text-sm bg-[#00FF6A]/10 border border-[#00FF6A]/30 text-[#00FF6A] hover:bg-[#00FF6A]/20 transition-colors disabled:opacity-50">
            {testAlert.loading ? '⏳ Versturen...' : '📧 Test versturen'}
          </button>
        </div>
        {testAlert.result && (
          <div className={`mt-3 text-xs p-2 rounded ${testAlert.error ? 'text-[#FF3B3B] bg-[#FF3B3B]/10' : 'text-[#00FF6A] bg-[#00FF6A]/10'}`}>
            {testAlert.result}
          </div>
        )}
      </div>

      <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>;
}
