import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogBody,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useToast } from '@/components/ui/use-toast';
import { Search, Copy, ArrowUpDown, AlertTriangle, ChevronDown, ChevronRight } from 'lucide-react';
import type { ThreadDetail } from '../types';
import { getThreadDump } from '../service';

interface ThreadDetailDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

type SortField = 'id' | 'blocked' | 'waited';
type SortOrder = 'asc' | 'desc';

// 线程状态颜色映射
const getStateColor = (state: string) => {
    switch (state) {
        case 'RUNNABLE':
            return 'default';
        case 'WAITING':
            return 'secondary';
        case 'TIMED_WAITING':
            return 'outline';
        case 'BLOCKED':
            return 'destructive';
        case 'NEW':
            return 'secondary';
        case 'TERMINATED':
            return 'outline';
        default:
            return 'secondary';
    }
};

export const ThreadDetailDialog: React.FC<ThreadDetailDialogProps> = ({
    open,
    onOpenChange,
}) => {
    const { toast } = useToast();
    const [threads, setThreads] = useState<ThreadDetail[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [selectedState, setSelectedState] = useState<string | null>(null);
    const [sortField, setSortField] = useState<SortField>('id');
    const [sortOrder, setSortOrder] = useState<SortOrder>('asc');
    const [expandedThreads, setExpandedThreads] = useState<Set<number>>(new Set());
    const [showProblemsOnly, setShowProblemsOnly] = useState(false);

    // 加载线程详情
    useEffect(() => {
        if (open) {
            loadThreads();
        }
    }, [open]);

    const loadThreads = async () => {
        setLoading(true);
        try {
            const data = await getThreadDump();
            setThreads(data.threads || []);
        } catch (error) {
            console.error('加载线程详情失败:', error);
        } finally {
            setLoading(false);
        }
    };

    // 过滤和排序线程
    const filteredThreads = threads
        .filter(thread => {
            // 仅显示问题线程
            if (showProblemsOnly) {
                const hasProblems = 
                    thread.threadState === 'BLOCKED' || 
                    thread.blockedCount > 5 || 
                    thread.waitedCount > 100;
                if (!hasProblems) return false;
            }

            // 状态筛选
            if (selectedState && thread.threadState !== selectedState) {
                return false;
            }
            
            // 关键词搜索
            if (!searchKeyword.trim()) return true;
            const keyword = searchKeyword.toLowerCase();
            return (
                thread.threadName.toLowerCase().includes(keyword) ||
                thread.threadState.toLowerCase().includes(keyword)
            );
        })
        .sort((a, b) => {
            let comparison = 0;
            
            switch (sortField) {
                case 'blocked':
                    comparison = a.blockedCount - b.blockedCount;
                    break;
                case 'waited':
                    comparison = a.waitedCount - b.waitedCount;
                    break;
                case 'id':
                default:
                    comparison = a.threadId - b.threadId;
                    break;
            }
            
            return sortOrder === 'asc' ? comparison : -comparison;
        });

    // 按状态分组统计
    const stateStats = threads.reduce((acc, thread) => {
        acc[thread.threadState] = (acc[thread.threadState] || 0) + 1;
        return acc;
    }, {} as Record<string, number>);

    // 复制线程详情（当前筛选的线程 + 完整堆栈）
    const handleCopyThreadDetails = () => {
        const details = filteredThreads.map(thread => {
            // 格式化堆栈信息
            const stackTrace = thread.stackTrace && thread.stackTrace.length > 0
                ? '\n堆栈信息:\n' + thread.stackTrace
                    .map(s => `    at ${s.className}.${s.methodName}(${s.fileName}:${s.lineNumber})`)
                    .join('\n')
                : '\n堆栈信息: 无';

            return `
线程ID: ${thread.threadId}
线程名称: ${thread.threadName}
线程状态: ${thread.threadState}
阻塞次数: ${thread.blockedCount}
阻塞时间: ${thread.blockedTime}ms
等待次数: ${thread.waitedCount}
等待时间: ${thread.waitedTime}ms
锁信息: ${thread.lockInfo ? '持有锁' : '无'}${stackTrace}
----------------------------------------`;
        }).join('\n');

        // 当前筛选条件说明
        let filterInfo = '';
        if (selectedState) {
            filterInfo += `\n筛选条件: 状态=${selectedState}`;
        }
        if (showProblemsOnly) {
            filterInfo += `\n筛选条件: 仅显示问题线程（BLOCKED 或 阻塞>5 或 等待>100）`;
        }
        if (searchKeyword) {
            filterInfo += `\n搜索关键词: ${searchKeyword}`;
        }
        if (sortField !== 'id') {
            filterInfo += `\n排序方式: ${sortField === 'blocked' ? '阻塞次数' : '等待次数'} (${sortOrder === 'desc' ? '降序' : '升序'})`;
        }

        const summary = `
=====================================
线程详情报告
=====================================
导出时间: ${new Date().toLocaleString('zh-CN')}
总线程数: ${threads.length} 个
显示线程数: ${filteredThreads.length} 个${filterInfo}
=====================================
状态统计:
${Object.entries(stateStats).map(([state, count]) => `  ${state}: ${count}`).join('\n')}
=====================================

${details}
=====================================
报告结束
=====================================
`;

        navigator.clipboard.writeText(summary).then(() => {
            toast({
                title: '✓ 复制成功',
                description: `已复制 ${filteredThreads.length} 个线程的详细信息（含堆栈）`,
            });
        }).catch(() => {
            toast({
                variant: 'destructive',
                title: '复制失败',
                description: '无法复制到剪贴板',
            });
        });
    };

    // 点击状态标签进行筛选
    const handleStateClick = (state: string) => {
        if (selectedState === state) {
            setSelectedState(null);
        } else {
            setSelectedState(state);
        }
    };

    // 切换排序
    const handleSort = (field: SortField) => {
        if (sortField === field) {
            // 切换排序方向
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            // 新字段，默认降序（问题线程在前）
            setSortField(field);
            setSortOrder('desc');
        }
    };

    // 展开/折叠线程堆栈
    const toggleThreadExpand = (threadId: number) => {
        const newExpanded = new Set(expandedThreads);
        if (newExpanded.has(threadId)) {
            newExpanded.delete(threadId);
        } else {
            newExpanded.add(threadId);
        }
        setExpandedThreads(newExpanded);
    };

    // 判断是否为问题线程
    const isProblemThread = (thread: ThreadDetail) => {
        return thread.threadState === 'BLOCKED' || 
               thread.blockedCount > 5 || 
               thread.waitedCount > 100;
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-6xl">
                <DialogHeader>
                    <DialogTitle>
                        <div className="flex items-center justify-between">
                            <span>线程详情 ({threads.length} 个线程)</span>
                            <div className="flex items-center gap-3">
                                {!loading && (
                                    <div className="flex items-center gap-2 text-sm font-normal">
                                        {Object.entries(stateStats).map(([state, count]) => (
                                            <Badge 
                                                key={state} 
                                                variant={getStateColor(state)}
                                                className={`cursor-pointer transition-all ${
                                                    selectedState === state 
                                                        ? 'ring-2 ring-offset-2 ring-primary' 
                                                        : 'hover:opacity-80'
                                                }`}
                                                onClick={() => handleStateClick(state)}
                                            >
                                                {state}: {count}
                                            </Badge>
                                        ))}
                                    </div>
                                )}
                                <Button
                                    variant={showProblemsOnly ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setShowProblemsOnly(!showProblemsOnly)}
                                    disabled={loading}
                                >
                                    <AlertTriangle className="h-4 w-4 mr-2" />
                                    {showProblemsOnly ? '显示全部' : '仅问题线程'}
                                </Button>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleCopyThreadDetails}
                                    disabled={loading || threads.length === 0}
                                >
                                    <Copy className="h-4 w-4 mr-2" />
                                    复制线程详情
                                </Button>
                            </div>
                        </div>
                    </DialogTitle>
                </DialogHeader>

                <DialogBody className="space-y-4">
                    {/* 搜索框 */}
                    <div className="space-y-2">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                                placeholder="搜索线程名称或状态..."
                                value={searchKeyword}
                                onChange={(e) => setSearchKeyword(e.target.value)}
                                className="pl-10"
                            />
                        </div>
                        {selectedState && (
                            <div className="flex items-center gap-2 text-sm">
                                <span className="text-muted-foreground">当前筛选：</span>
                                <Badge variant={getStateColor(selectedState)}>
                                    {selectedState}
                                </Badge>
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => setSelectedState(null)}
                                    className="h-6 px-2 text-xs"
                                >
                                    清除筛选
                                </Button>
                            </div>
                        )}
                    </div>

                    {/* 线程列表 */}
                    {loading ? (
                        <div className="space-y-2">
                            {[1, 2, 3, 4, 5].map(i => (
                                <Skeleton key={i} className="h-16 w-full" />
                            ))}
                        </div>
                    ) : (
                        <div className="border rounded-lg">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="w-[40px]"></TableHead>
                                        <TableHead 
                                            className="w-[50px] cursor-pointer hover:bg-muted/50"
                                            onClick={() => handleSort('id')}
                                        >
                                            <div className="flex items-center gap-1">
                                                ID
                                                {sortField === 'id' && <ArrowUpDown className="h-3 w-3" />}
                                            </div>
                                        </TableHead>
                                        <TableHead className="w-[200px]">线程名称</TableHead>
                                        <TableHead className="w-[110px]">状态</TableHead>
                                        <TableHead 
                                            className="w-[90px] cursor-pointer hover:bg-muted/50"
                                            onClick={() => handleSort('blocked')}
                                        >
                                            <div className="flex items-center gap-1 text-xs">
                                                阻塞次数
                                                {sortField === 'blocked' && <ArrowUpDown className="h-3 w-3" />}
                                            </div>
                                        </TableHead>
                                        <TableHead 
                                            className="w-[90px] cursor-pointer hover:bg-muted/50"
                                            onClick={() => handleSort('waited')}
                                        >
                                            <div className="flex items-center gap-1 text-xs">
                                                等待次数
                                                {sortField === 'waited' && <ArrowUpDown className="h-3 w-3" />}
                                            </div>
                                        </TableHead>
                                        <TableHead className="w-[80px]">锁信息</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {filteredThreads.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                                                {searchKeyword ? '未找到匹配的线程' : '暂无线程数据'}
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        filteredThreads.map((thread) => {
                                            const isExpanded = expandedThreads.has(thread.threadId);
                                            const hasProblem = isProblemThread(thread);
                                            
                                            return (
                                                <React.Fragment key={thread.threadId}>
                                                    <TableRow className={hasProblem ? 'bg-red-50 dark:bg-red-950/10' : ''}>
                                                        <TableCell className="text-center">
                                                            <Button
                                                                variant="ghost"
                                                                size="sm"
                                                                className="h-6 w-6 p-0"
                                                                onClick={() => toggleThreadExpand(thread.threadId)}
                                                            >
                                                                {isExpanded ? (
                                                                    <ChevronDown className="h-4 w-4" />
                                                                ) : (
                                                                    <ChevronRight className="h-4 w-4" />
                                                                )}
                                                            </Button>
                                                        </TableCell>
                                                        <TableCell className="font-mono text-xs">
                                                            {thread.threadId}
                                                        </TableCell>
                                                        <TableCell className="font-mono text-xs max-w-[200px]">
                                                            <div className="flex items-center gap-1.5">
                                                                {hasProblem && (
                                                                    <AlertTriangle className="h-3.5 w-3.5 text-red-600 flex-shrink-0" />
                                                                )}
                                                                <span className="truncate" title={thread.threadName}>
                                                                    {thread.threadName}
                                                                </span>
                                                            </div>
                                                        </TableCell>
                                                        <TableCell>
                                                            <Badge variant={getStateColor(thread.threadState)}>
                                                                {thread.threadState}
                                                            </Badge>
                                                        </TableCell>
                                                        <TableCell className="text-center">
                                                            {thread.blockedCount > 0 ? (
                                                                <span className={`font-medium ${
                                                                    thread.blockedCount > 5 
                                                                        ? 'text-red-600' 
                                                                        : 'text-orange-600'
                                                                }`}>
                                                                    {thread.blockedCount}
                                                                </span>
                                                            ) : (
                                                                <span className="text-muted-foreground">0</span>
                                                            )}
                                                        </TableCell>
                                                        <TableCell className="text-center">
                                                            <span className={thread.waitedCount > 100 ? 'text-orange-600 font-medium' : 'text-muted-foreground'}>
                                                                {thread.waitedCount}
                                                            </span>
                                                        </TableCell>
                                                        <TableCell className="text-xs">
                                                            {thread.lockInfo ? (
                                                                <span className="text-orange-600">持有锁</span>
                                                            ) : (
                                                                <span className="text-muted-foreground">-</span>
                                                            )}
                                                        </TableCell>
                                                    </TableRow>
                                                    {isExpanded && (
                                                        <TableRow>
                                                            <TableCell colSpan={7} className="bg-muted/30 p-4">
                                                                <div className="space-y-2">
                                                                    <div className="flex items-center justify-between">
                                                                        <h4 className="font-medium text-sm">线程堆栈信息</h4>
                                                                        <Button
                                                                            variant="outline"
                                                                            size="sm"
                                                                            onClick={() => {
                                                                                const stack = thread.stackTrace
                                                                                    .map(s => `    at ${s.className}.${s.methodName}(${s.fileName}:${s.lineNumber})`)
                                                                                    .join('\n');
                                                                                navigator.clipboard.writeText(`线程 #${thread.threadId}: ${thread.threadName}\n${stack}`);
                                                                                toast({ title: '已复制堆栈信息' });
                                                                            }}
                                                                        >
                                                                            <Copy className="h-3 w-3 mr-1" />
                                                                            复制堆栈
                                                                        </Button>
                                                                    </div>
                                                                    <div className="bg-background rounded border p-3 font-mono text-xs overflow-x-auto max-h-64 overflow-y-auto">
                                                                        {thread.stackTrace && thread.stackTrace.length > 0 ? (
                                                                            thread.stackTrace.map((stack, idx) => (
                                                                                <div 
                                                                                    key={idx} 
                                                                                    className={`py-0.5 ${
                                                                                        stack.className?.includes('Lock') || 
                                                                                        stack.methodName?.includes('lock') ||
                                                                                        stack.methodName?.includes('wait')
                                                                                            ? 'text-orange-600 font-medium' 
                                                                                            : 'text-muted-foreground'
                                                                                    }`}
                                                                                >
                                                                                    at {stack.className}.{stack.methodName}
                                                                                    ({stack.fileName}:{stack.lineNumber})
                                                                                </div>
                                                                            ))
                                                                        ) : (
                                                                            <div className="text-muted-foreground">无堆栈信息</div>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            </TableCell>
                                                        </TableRow>
                                                    )}
                                                </React.Fragment>
                                            );
                                        })
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    )}

                    {/* 底部统计 */}
                    <div className="text-xs text-muted-foreground text-center">
                        显示 {filteredThreads.length} / {threads.length} 个线程
                    </div>
                </DialogBody>
            </DialogContent>
        </Dialog>
    );
};
