import React, { useState, useEffect } from 'react';
import { 
  Terminal, Search, Download, Trash2, Activity, RefreshCw, 
  CheckCircle2, AlertTriangle, XCircle, Info, Pause, Play
} from 'lucide-react';

interface TelemetryLogsViewProps {
  api: any;
}

export function TelemetryLogsView({ api }: TelemetryLogsViewProps) {
  const [logs, setLogs] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [levelFilter, setLevelFilter] = useState<'ALL' | 'INFO' | 'WARN' | 'ERROR'>('ALL');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [instances, setInstances] = useState<Array<{ id: string; name?: string; status: string }>>([]);
  const [selectedInstanceId, setSelectedInstanceId] = useState<string | null>(null);

  const fetchInstances = async () => {
    try {
      const res = await api.get('/instances');
      const list = Array.isArray(res.data) ? res.data : [];
      setInstances(list);
      if (!selectedInstanceId && list.length > 0) {
        setSelectedInstanceId(list[0].id);
      }
    } catch (err) {
      // swallow — keep last good list
    }
  };

  const fetchLogs = async () => {
    if (!selectedInstanceId) {
      setLogs([]);
      return;
    }
    setLoading(true);
    try {
      const res = await api.get(`/instances/${selectedInstanceId}/logs`);
      const lines = Array.isArray(res.data) ? res.data : [];
      setLogs(lines);
    } catch (err: any) {
      const timeStr = new Date().toLocaleTimeString();
      setLogs(prev => prev.length ? prev : [`[${timeStr}] [ERROR] Failed to fetch instance logs: ${err.message || 'unknown'}`]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchInstances(); }, []);

  useEffect(() => {
    fetchLogs();
    if (!autoRefresh || !selectedInstanceId) return;
    const interval = setInterval(fetchLogs, 3000);
    return () => clearInterval(interval);
  }, [autoRefresh, selectedInstanceId]);

  const filteredLogs = logs.filter(log => {
    const matchesLevel = 
      levelFilter === 'ALL' ? true :
      levelFilter === 'ERROR' ? log.includes('ERROR') :
      levelFilter === 'WARN' ? log.includes('WARN') :
      log.includes('INFO');

    const matchesSearch = searchQuery === '' || log.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesLevel && matchesSearch;
  });

  const handleDownloadLogs = () => {
    const blob = new Blob([logs.join('\n')], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    const safeId = selectedInstanceId ? selectedInstanceId.replace(/[^a-z0-9_-]/gi, '_') : 'global';
    link.download = `superadmin_${safeId}_${new Date().toISOString().slice(0, 10)}.log`;
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-xl space-y-0">
      {/* Terminal Toolbar */}
      <div className="p-5 bg-muted/40 border-b border-border flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-slate-950 border border-slate-800 text-emerald-400 flex items-center justify-center shadow-inner">
            <Terminal size={20} />
          </div>
          <div>
            <h2 className="text-base font-bold text-foreground flex items-center gap-2">
              Tenant Telemetry Stream
              {autoRefresh && (
                <span className="flex items-center gap-1 text-[0.65rem] font-mono text-emerald-500 font-bold px-2 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20">
                  <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" /> LIVE STREAM
                </span>
              )}
            </h2>
            <p className="text-xs text-muted-foreground mt-0.5">Live stdout/stderr from spawned school instances, polled every 3s from the orchestrator's persisted log buffer.</p>
          </div>
        </div>

        {/* Filter Controls */}
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative min-w-[200px]">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search log stream..."
              className="w-full pl-9 pr-3 py-1.5 bg-background border border-border rounded-xl text-foreground text-xs font-mono focus:outline-none focus:border-primary"
            />
          </div>

          <select
            value={selectedInstanceId ?? ''}
            onChange={e => setSelectedInstanceId(e.target.value || null)}
            className="py-1.5 px-3 bg-background border border-border rounded-xl text-xs font-mono text-foreground focus:outline-none min-w-[180px]"
          >
            <option value="">— Select instance —</option>
            {instances.map(ins => (
              <option key={ins.id} value={ins.id}>
                {(ins.name || ins.id).slice(0, 32)} {ins.status ? `· ${ins.status}` : ''}
              </option>
            ))}
          </select>

          <select
            value={levelFilter}
            onChange={e => setLevelFilter(e.target.value as any)}
            className="py-1.5 px-3 bg-background border border-border rounded-xl text-xs font-mono text-foreground focus:outline-none"
          >
            <option value="ALL">All Levels</option>
            <option value="INFO">INFO Only</option>
            <option value="WARN">WARN Only</option>
            <option value="ERROR">ERROR Only</option>
          </select>

          <button
            onClick={() => setAutoRefresh(!autoRefresh)}
            className={`p-2 rounded-xl border text-xs font-bold transition-all ${autoRefresh ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/30' : 'bg-background text-muted-foreground border-border'}`}
            title={autoRefresh ? 'Pause Stream' : 'Resume Stream'}
          >
            {autoRefresh ? <Pause size={16} /> : <Play size={16} />}
          </button>

          <button
            onClick={() => setLogs([])}
            className="p-2 rounded-xl bg-background hover:bg-muted text-muted-foreground hover:text-rose-500 border border-border transition-all"
            title="Clear Log View"
          >
            <Trash2 size={16} />
          </button>

          <button
            onClick={handleDownloadLogs}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-primary hover:bg-primary-dark text-white rounded-xl text-xs font-bold transition-all shadow-sm"
          >
            <Download size={14} /> Export Logs
          </button>
        </div>
      </div>

      {/* Log Terminal Display Window */}
      <div className="bg-[#050811] p-6 font-mono text-[0.75rem] text-slate-200 h-[480px] overflow-y-auto custom-scrollbar space-y-2 select-text">
        {filteredLogs.length > 0 ? (
          filteredLogs.map((log, idx) => {
            const isError = log.includes('[ERROR]');
            const isWarn = log.includes('[WARN]');
            return (
              <div 
                key={idx} 
                className={`p-2 rounded-lg border transition-colors flex items-start gap-2 ${
                  isError ? 'bg-rose-950/40 border-rose-500/30 text-rose-300' :
                  isWarn ? 'bg-amber-950/40 border-amber-500/30 text-amber-300' :
                  'bg-slate-900/40 border-slate-800/60 text-emerald-400'
                }`}
              >
                {isError ? <XCircle size={14} className="text-rose-400 mt-0.5 flex-shrink-0" /> :
                 isWarn ? <AlertTriangle size={14} className="text-amber-400 mt-0.5 flex-shrink-0" /> :
                 <Info size={14} className="text-emerald-400 mt-0.5 flex-shrink-0" />}
                <span className="break-all">{log}</span>
              </div>
            );
          })
        ) : (
          <div className="h-full flex items-center justify-center text-slate-600">
            {selectedInstanceId
              ? 'No telemetry log entries matching active filter parameters.'
              : 'Select a spawned school instance above to view its stdout/stderr stream.'}
          </div>
        )}
      </div>
    </div>
  );
}
