import React, { useEffect, useRef } from 'react';
import { Terminal, Clock, AlertCircle, Info, CheckCircle, Activity } from 'lucide-react';

export interface LogEntry {
    level: string;
    message: string;
    timestamp: string;
}

interface LogViewerProps {
    logs: LogEntry[];
}

const LogViewer: React.FC<LogViewerProps> = ({ logs }) => {
    const endRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        endRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [logs]);

    const getIcon = (level: string) => {
        switch (level) {
            case 'ERROR': return <AlertCircle size={14} className="text-destructive mb-0.5" />;
            case 'WARN': return <AlertCircle size={14} className="text-yellow-500 mb-0.5" />;
            case 'SUCCESS': return <CheckCircle size={14} className="text-green-500 mb-0.5" />;
            case 'DEBUG': return <Activity size={14} className="text-blue-400 mb-0.5" />;
            default: return <Info size={14} className="text-primary mb-0.5" />;
        }
    };

    const getColor = (level: string) => {
        switch (level) {
            case 'ERROR': return 'text-destructive';
            case 'WARN': return 'text-yellow-500';
            case 'SUCCESS': return 'text-green-500';
            case 'DEBUG': return 'text-muted-foreground';
            default: return 'text-foreground';
        }
    };

    const handleExportLogs = () => {
        const text = logs.map(l => `[${l.timestamp}] [${l.level}] ${l.message}`).join('\n');
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `hearbit_logs_${new Date().toISOString().slice(0, 10)}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    return (
        <div className="flex flex-col h-full bg-background font-mono text-sm">
            <div className="p-3 border-b border-border/40 bg-secondary/20 flex justify-between items-center">
                <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">System Logs</span>
                <button
                    onClick={handleExportLogs}
                    className="text-xs bg-secondary hover:bg-secondary/80 text-foreground px-2 py-1 rounded border border-border transition-colors flex items-center gap-1"
                >
                    <Terminal size={12} className="inline mr-1" /> Export .txt
                </button>
            </div>
            <div className="flex-1 overflow-y-auto p-4 space-y-1">
                {logs.length === 0 && (
                    <div className="text-muted-foreground opacity-50 text-center mt-10 italic">
                        No logs yet...
                    </div>
                )}
                {logs.map((log, i) => (
                    <div key={i} className="flex gap-3 py-1.5 px-3 hover:bg-secondary/30 rounded-md transition-colors items-start">
                        <span className="text-muted-foreground/60 text-xs mt-0.5 shrink-0 select-none flex items-center gap-1.5 min-w-[70px]">
                            <Clock size={10} />
                            {log.timestamp}
                        </span>
                        <div className={`mt-0.5 shrink-0 ${getColor(log.level)}`}>
                            {getIcon(log.level)}
                        </div>
                        <span className={`break-all ${getColor(log.level)}`}>
                            {log.message}
                        </span>
                    </div>
                ))}
                <div ref={endRef} />
            </div>
        </div>
    );
};

export default LogViewer;
