import { useState, useEffect, useRef } from 'react'
import { Terminal, Trash2, Play, Pause } from 'lucide-react'
import { Card, CardHeader, CardTitle, CardContent, Button } from '../common'

interface LogEntry {
    timestamp: string
    level: string
    message: string
    email?: string
    step?: string
}

interface LogStreamProps {
    apiBase?: string
}

const levelColors: Record<string, string> = {
    info: 'text-blue-400',
    success: 'text-green-400',
    warning: 'text-yellow-400',
    error: 'text-red-400',
}

const stepColors: Record<string, string> = {
    validate: 'bg-purple-500/20 text-purple-400',
    register: 'bg-blue-500/20 text-blue-400',
    authorize: 'bg-orange-500/20 text-orange-400',
    pool: 'bg-green-500/20 text-green-400',
    database: 'bg-slate-500/20 text-slate-400',
}

const stepLabels: Record<string, string> = {
    validate: '验证',
    register: '注册',
    authorize: '授权',
    pool: '入库',
    database: '数据库',
}

export default function LogStream({ apiBase = 'http://localhost:8088' }: LogStreamProps) {
    const [logs, setLogs] = useState<LogEntry[]>([])
    const [connected, setConnected] = useState(false)
    const [paused, setPaused] = useState(false)
    const logContainerRef = useRef<HTMLDivElement>(null)
    const eventSourceRef = useRef<EventSource | null>(null)

    useEffect(() => {
        if (paused) return

        const eventSource = new EventSource(`${apiBase}/api/logs/stream`)
        eventSourceRef.current = eventSource

        eventSource.onopen = () => {
            setConnected(true)
        }

        eventSource.onmessage = (event) => {
            try {
                const log = JSON.parse(event.data) as LogEntry
                setLogs((prev) => [...prev.slice(-199), log])
            } catch (e) {
                console.error('Failed to parse log:', e)
            }
        }

        eventSource.onerror = () => {
            setConnected(false)
            eventSource.close()
        }

        return () => {
            eventSource.close()
        }
    }, [apiBase, paused])

    useEffect(() => {
        if (logContainerRef.current) {
            logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
        }
    }, [logs])

    const handleClear = async () => {
        try {
            await fetch(`${apiBase}/api/logs/clear`, { method: 'POST' })
            setLogs([])
        } catch (e) {
            console.error('Failed to clear logs:', e)
        }
    }

    const togglePause = () => {
        if (!paused && eventSourceRef.current) {
            eventSourceRef.current.close()
        }
        setPaused(!paused)
    }

    const formatTime = (timestamp: string) => {
        try {
            return new Date(timestamp).toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
            })
        } catch {
            return ''
        }
    }

    return (
        <Card className="h-full flex flex-col">
            <CardHeader className="flex-shrink-0">
                <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center gap-2">
                        <Terminal className="h-5 w-5" />
                        实时日志
                        <span
                            className={`w-2 h-2 rounded-full ${connected ? 'bg-green-500' : 'bg-red-500'}`}
                        />
                    </CardTitle>
                    <div className="flex gap-2">
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={togglePause}
                            icon={paused ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}
                        >
                            {paused ? '继续' : '暂停'}
                        </Button>
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={handleClear}
                            icon={<Trash2 className="h-4 w-4" />}
                        >
                            清空
                        </Button>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="flex-1 overflow-hidden p-0">
                <div
                    ref={logContainerRef}
                    className="h-full overflow-y-auto bg-slate-900 dark:bg-slate-950 p-4 font-mono text-xs"
                >
                    {logs.length === 0 ? (
                        <div className="text-slate-500 text-center py-8">等待日志...</div>
                    ) : (
                        logs.map((log, i) => (
                            <div key={i} className="flex gap-2 py-0.5 hover:bg-slate-800/50">
                                <span className="text-slate-500 flex-shrink-0">{formatTime(log.timestamp)}</span>
                                {log.step && (
                                    <span
                                        className={`px-1.5 rounded text-[10px] uppercase flex-shrink-0 ${stepColors[log.step] || 'bg-slate-500/20 text-slate-400'}`}
                                    >
                                        {stepLabels[log.step] || log.step}
                                    </span>
                                )}
                                <span className={`flex-shrink-0 ${levelColors[log.level] || 'text-slate-300'}`}>
                                    {log.level === 'success' ? '✓' : log.level === 'error' ? '✗' : '•'}
                                </span>
                                <span className="text-slate-300 break-all">{log.message}</span>
                                {log.email && (
                                    <span className="text-slate-500 flex-shrink-0 ml-auto">[{log.email}]</span>
                                )}
                            </div>
                        ))
                    )}
                </div>
            </CardContent>
        </Card>
    )
}
