import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { Play, CheckCircle2, AlertCircle, Clock } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Badge, Button, Card } from '../../components/ui/primitives';

interface CronDef {
  name: string;
  schedule: string;
  description: string;
  last_run: {
    started_at: string;
    finished_at: string | null;
    status: string;
    output_summary: string | null;
    error_message: string | null;
    duration_secs: number | null;
  } | null;
}

const STATUS_ICON: Record<string, React.ReactNode> = {
  completed: <CheckCircle2 className="h-4 w-4 text-[#00FF6A]" />,
  running: <Play className="h-4 w-4 text-[#3B82F6]" />,
  triggered: <Clock className="h-4 w-4 text-[#FFA500]" />,
  failed: <AlertCircle className="h-4 w-4 text-[#FF3B3B]" />,
};

const STATUS_VARIANTS: Record<string, 'success' | 'info' | 'warn' | 'danger' | 'muted'> = {
  completed: 'success',
  running: 'info',
  triggered: 'warn',
  failed: 'danger',
};

export function CronMonitor() {
  const qc = useQueryClient();
  const { data } = useQuery({
    queryKey: ['crons'],
    queryFn: () => api.get<{ crons: CronDef[] }>('/crons'),
    refetchInterval: 15000,
  });

  const triggerMut = useMutation({
    mutationFn: (name: string) => api.post('/crons', { name }),
    onSuccess: (_r, name) => {
      toast.success(`Cron "${name}" getriggerd`);
      qc.invalidateQueries({ queryKey: ['crons'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const crons = data?.crons ?? [];

  return (
    <AppShell>
      <PageHeader
        title="Cron monitor"
        description="Geplande taken, laatste runs en handmatig triggeren."
      />
      <PageBody>
        <div className="grid grid-cols-2 gap-4">
          {crons.map((c) => {
            const last = c.last_run;
            return (
              <Card key={c.name} className="overflow-hidden">
                <div className="px-5 py-4 border-b border-[#333] flex items-start justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="text-sm font-semibold text-[#F5F5F5]">{c.name}</h3>
                      {last && <Badge variant={STATUS_VARIANTS[last.status] ?? 'muted'}>{last.status}</Badge>}
                    </div>
                    <p className="text-xs text-[#999] mt-1">{c.description}</p>
                    <p className="text-xs text-[#666] mt-1 font-mono">{c.schedule}</p>
                  </div>
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={() => {
                      if (confirm(`Cron "${c.name}" handmatig starten?`)) triggerMut.mutate(c.name);
                    }}
                    disabled={triggerMut.isPending}
                  >
                    <Play className="h-3 w-3" />
                    Trigger
                  </Button>
                </div>
                <div className="px-5 py-3 text-xs space-y-1.5">
                  {last ? (
                    <>
                      <div className="flex items-center gap-2">
                        {STATUS_ICON[last.status] ?? null}
                        <span className="text-[#999]">Laatst:</span>
                        <span className="text-[#F5F5F5] font-mono">
                          {new Date(last.started_at).toLocaleString('nl-NL')}
                        </span>
                        {last.duration_secs !== null && (
                          <span className="text-[#666]">({last.duration_secs}s)</span>
                        )}
                      </div>
                      {last.output_summary && (
                        <p className="text-[#999] italic truncate">{last.output_summary}</p>
                      )}
                      {last.error_message && (
                        <p className="text-[#FF3B3B] font-mono text-[11px]">{last.error_message}</p>
                      )}
                    </>
                  ) : (
                    <p className="text-[#666] italic">Nog nooit gedraaid.</p>
                  )}
                </div>
              </Card>
            );
          })}
        </div>
        {crons.length === 0 && (
          <Card>
            <div className="p-10 text-center text-sm text-[#666]">Geen crons geconfigureerd.</div>
          </Card>
        )}
      </PageBody>
    </AppShell>
  );
}
