'use client';

import { useEffect, useRef, useState } from 'react';
import { Terminal, Trash2, Pause, Play, Circle } from 'lucide-react';

type ServiceFilter = 'all' | 'app' | 'postgres';

interface LogLine {
  id: number;
  text: string;
}

const SERVICES: { key: ServiceFilter; label: string }[] = [
  { key: 'all', label: 'Alle Services' },
  { key: 'app', label: 'app' },
  { key: 'postgres', label: 'postgres' },
];

export default function AdminLogsPage() {
  const [service, setService] = useState<ServiceFilter>('all');
  const [lines, setLines] = useState<LogLine[]>([]);
  const [status, setStatus] = useState<'connecting' | 'live' | 'error'>('connecting');
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [paused, setPaused] = useState(false);
  const [autoScroll, setAutoScroll] = useState(true);

  const nextId = useRef(0);
  const bufferRef = useRef<LogLine[]>([]);
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const pausedRef = useRef(paused);
  pausedRef.current = paused;

  useEffect(() => {
    setLines([]);
    bufferRef.current = [];
    setStatus('connecting');
    setErrorMessage(null);

    const url = `/api/admin/logs/stream${service === 'all' ? '' : `?service=${service}`}`;
    const es = new EventSource(url);

    es.onopen = () => setStatus('live');

    es.onmessage = (evt) => {
      if (pausedRef.current) return;
      const id = nextId.current++;
      setLines((prev) => {
        const next = [...prev, { id, text: evt.data }];
        return next.length > 2000 ? next.slice(next.length - 2000) : next;
      });
    };

    es.addEventListener('fatal', (evt: MessageEvent) => {
      setStatus('error');
      setErrorMessage(evt.data || 'Verbindung zum Docker-Log-Stream verloren.');
      es.close();
    });

    es.onerror = () => {
      setStatus('error');
    };

    return () => es.close();
  }, [service]);

  useEffect(() => {
    if (!autoScroll || paused) return;
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [lines, autoScroll, paused]);

  const handleScroll = () => {
    const el = scrollRef.current;
    if (!el) return;
    const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
    setAutoScroll(atBottom);
  };

  const statusBadge = () => {
    if (status === 'live') {
      return (
        <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
          <Circle size={8} className="fill-emerald-500 text-emerald-500 animate-pulse" /> Live
        </span>
      );
    }
    if (status === 'error') {
      return (
        <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-red-700 bg-red-50 px-2.5 py-1 rounded-full border border-red-200">
          <Circle size={8} className="fill-red-500 text-red-500" /> Getrennt
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1.5 text-xs font-medium text-slate-500 bg-slate-100 px-2.5 py-1 rounded-full border border-slate-200">
        <Circle size={8} className="fill-slate-400 text-slate-400" /> Verbinde...
      </span>
    );
  };

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between pb-2 border-b border-slate-200 flex-wrap gap-3">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans flex items-center gap-2.5">
            <Terminal size={26} className="text-slate-700" />
            Docker Logs
          </h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">
            Live-Ausgabe von <code className="font-mono">docker compose logs -f</code> (letzte 300 Zeilen + Live-Follow).
          </p>
        </div>
        {statusBadge()}
      </div>

      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-1.5 bg-slate-100 border border-slate-200 rounded-xl p-1">
          {SERVICES.map((s) => (
            <button
              key={s.key}
              onClick={() => setService(s.key)}
              className={`px-3.5 py-1.5 rounded-lg text-xs font-mono font-semibold transition-all ${
                service === s.key
                  ? 'bg-slate-900 text-white shadow-xs'
                  : 'text-slate-600 hover:text-slate-900 hover:bg-white'
              }`}
            >
              {s.label}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => setPaused((p) => !p)}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 bg-white border border-slate-200 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-colors shadow-xs"
          >
            {paused ? <Play size={14} /> : <Pause size={14} />}
            {paused ? 'Fortsetzen' : 'Pausieren'}
          </button>
          <button
            onClick={() => setLines([])}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 bg-white border border-slate-200 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-colors shadow-xs"
          >
            <Trash2 size={14} />
            Leeren
          </button>
        </div>
      </div>

      {status === 'error' && errorMessage && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl text-xs text-red-700 font-mono">
          {errorMessage}
          <p className="mt-1 text-red-600 font-sans">
            Läuft die App außerhalb von Docker (z.B. via <code className="font-mono">npm run dev</code>) mit
            Zugriff auf Docker Desktop? Im produktiv containerisierten Deployment ist die Docker-CLI im
            App-Container standardmäßig nicht verfügbar.
          </p>
        </div>
      )}

      <div
        ref={scrollRef}
        onScroll={handleScroll}
        className="bg-slate-950 border border-slate-800 rounded-2xl p-4 h-[65vh] overflow-y-auto font-mono text-[12px] leading-relaxed shadow-xs"
      >
        {lines.length === 0 ? (
          <p className="text-slate-500">Warte auf Log-Ausgabe...</p>
        ) : (
          lines.map((l) => (
            <div key={l.id} className="whitespace-pre-wrap break-all text-slate-300">
              {l.text}
            </div>
          ))
        )}
      </div>
      {!autoScroll && (
        <button
          onClick={() => {
            setAutoScroll(true);
            const el = scrollRef.current;
            if (el) el.scrollTop = el.scrollHeight;
          }}
          className="fixed bottom-8 right-8 px-4 py-2 bg-slate-900 text-white rounded-full text-xs font-semibold shadow-lg hover:bg-slate-800 transition-colors"
        >
          Zum Ende scrollen
        </button>
      )}
    </div>
  );
}
