import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogBody,
} from '@/components/ui/dialog';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DataTablePagination } from '@/components/ui/pagination';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import {
    FileText,
    Loader2,
    CheckCircle2,
    XCircle,
    Clock,
    Server,
    Calendar,
    AlertCircle,
    Timer,
    Code,
    Info,
    Activity,
    RefreshCw,
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { getJobLogs } from '../service';
import type { ScheduleJobResponse, ScheduleJobLogResponse, ScheduleJobLogQuery, LogStatus } from '../types';
import type { Page } from '@/types/base';
import dayjs from 'dayjs';
import { cn } from '@/lib/utils';

interface JobLogDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    job: ScheduleJobResponse | null;
}

const JobLogDialog: React.FC<JobLogDialogProps> = ({
    open,
    onOpenChange,
    job
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<Page<ScheduleJobLogResponse> | null>(null);
    const [selectedLog, setSelectedLog] = useState<ScheduleJobLogResponse | null>(null);
    const [query, setQuery] = useState<ScheduleJobLogQuery>({
        pageNum: DEFAULT_PAGE_NUM,
        pageSize: DEFAULT_PAGE_SIZE,
        jobId: undefined,
        status: undefined,
    });

    // 加载日志列表
    const loadLogs = async () => {
        if (!job) return;
        
        setLoading(true);
        try {
            const result = await getJobLogs({
                ...query,
                jobId: job.id,
            });
            setData(result);
        } catch (error) {
            console.error('加载日志失败:', error);
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '加载执行日志失败',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open && job) {
            loadLogs();
        }
    }, [open, job, query]);

    // 重置查询条件
    useEffect(() => {
        if (open && job) {
            setQuery({
                pageNum: 0,
                pageSize: DEFAULT_PAGE_SIZE,
                jobId: job.id,
                status: undefined,
            });
            setSelectedLog(null);
        }
    }, [open, job]);

    // 状态徽章
    const getStatusBadge = (status: LogStatus) => {
        const statusMap: Record<LogStatus, {
            variant: 'default' | 'secondary' | 'destructive';
            text: string;
            icon: React.ElementType
        }> = {
            SUCCESS: { variant: 'default', text: '成功', icon: CheckCircle2 },
            FAIL: { variant: 'destructive', text: '失败', icon: XCircle },
            TIMEOUT: { variant: 'secondary', text: '超时', icon: Clock },
        };
        const statusInfo = statusMap[status];
        const Icon = statusInfo.icon;
        return (
            <Badge variant={statusInfo.variant} className="inline-flex items-center gap-1">
                <Icon className="h-3 w-3" />
                {statusInfo.text}
            </Badge>
        );
    };

    // 格式化耗时
    const formatDuration = (duration?: number) => {
        if (!duration) return '-';
        if (duration < 1000) return `${duration}ms`;
        if (duration < 60000) return `${(duration / 1000).toFixed(2)}s`;
        return `${(duration / 60000).toFixed(2)}min`;
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-7xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <FileText className="h-5 w-5 text-primary" />
                        执行日志 - {job?.jobName}
                    </DialogTitle>
                </DialogHeader>

                <DialogBody className="space-y-4">
                    {/* 筛选栏 */}
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <Select
                                value={query.status || 'all'}
                                onValueChange={(value) => setQuery({ ...query, status: value !== 'all' ? value as LogStatus : undefined, pageNum: 0 })}
                            >
                                <SelectTrigger className="w-[160px]">
                                    <SelectValue placeholder="全部状态" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">全部状态</SelectItem>
                                    <SelectItem value="SUCCESS">✓ 成功</SelectItem>
                                    <SelectItem value="FAIL">✗ 失败</SelectItem>
                                    <SelectItem value="TIMEOUT">⏱ 超时</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <Button variant="outline" size="sm" onClick={loadLogs} disabled={loading}>
                            <RefreshCw className={cn("h-4 w-4 mr-2", loading && "animate-spin")} />
                            刷新
                        </Button>
                    </div>

                    {/* 日志列表 */}
                    {loading ? (
                        <div className="flex items-center justify-center h-64">
                            <div className="text-center">
                                <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2 text-primary" />
                                <p className="text-sm text-muted-foreground">加载中...</p>
                            </div>
                        </div>
                    ) : data && data.content.length > 0 ? (
                        <div className="grid grid-cols-2 gap-4">
                            {/* 左侧：日志列表 */}
                            <div className="space-y-2">
                                <ScrollArea className="h-[500px] pr-4">
                                    {data.content.map((log) => (
                                        <Card
                                            key={log.id}
                                            className={cn(
                                                "mb-3 cursor-pointer transition-all hover:shadow-md",
                                                selectedLog?.id === log.id
                                                    ? "border-primary bg-accent"
                                                    : "hover:border-muted-foreground/30"
                                            )}
                                            onClick={() => setSelectedLog(log)}
                                        >
                                            <CardContent className="p-4">
                                                <div className="flex items-start justify-between mb-3">
                                                    <div className="flex items-center gap-2">
                                                        {getStatusBadge(log.status)}
                                                        <span className="text-xs text-muted-foreground font-mono">
                                                            {formatDuration(log.duration)}
                                                        </span>
                                                    </div>
                                                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                                                        <Calendar className="h-3 w-3" />
                                                        {dayjs(log.executeTime).format('MM-DD HH:mm:ss')}
                                                    </div>
                                                </div>

                                                <div className="space-y-2">
                                                    {log.serverIp && (
                                                        <div className="flex items-center gap-2 text-xs">
                                                            <Server className="h-3.5 w-3.5 text-muted-foreground" />
                                                            <span className="font-mono">{log.serverIp}</span>
                                                        </div>
                                                    )}
                                                    {log.resultMessage && (
                                                        <p className="text-xs text-muted-foreground line-clamp-2">
                                                            {log.resultMessage}
                                                        </p>
                                                    )}
                                                </div>
                                            </CardContent>
                                        </Card>
                                    ))}
                                </ScrollArea>

                                {/* 分页 */}
                                {data && data.content.length > 0 && (
                                    <DataTablePagination
                                        pageIndex={query.pageNum || 0}
                                        pageSize={query.pageSize || DEFAULT_PAGE_SIZE}
                                        pageCount={data.totalPages}
                                        onPageChange={(pageIndex) => setQuery({ ...query, pageNum: pageIndex })}
                                    />
                                )}
                            </div>

                            {/* 右侧：详情面板 */}
                            <div className="border rounded-lg">
                                {selectedLog ? (
                                    <ScrollArea className="h-[556px]">
                                        <div className="p-5 space-y-4">
                                            <div className="flex items-center justify-between">
                                                <h3 className="text-base font-semibold flex items-center gap-2">
                                                    <Info className="h-4 w-4 text-primary" />
                                                    执行详情
                                                </h3>
                                                {getStatusBadge(selectedLog.status)}
                                            </div>

                                            <Separator />

                                            {/* 基本信息 */}
                                            <div className="space-y-3">
                                                <div className="flex items-start gap-3">
                                                    <Calendar className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                    <div className="flex-1">
                                                        <p className="text-xs text-muted-foreground mb-1">执行时间</p>
                                                        <p className="text-sm font-medium">
                                                            {dayjs(selectedLog.executeTime).format('YYYY-MM-DD HH:mm:ss')}
                                                        </p>
                                                    </div>
                                                </div>

                                                {selectedLog.finishTime && (
                                                    <div className="flex items-start gap-3">
                                                        <CheckCircle2 className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                        <div className="flex-1">
                                                            <p className="text-xs text-muted-foreground mb-1">完成时间</p>
                                                            <p className="text-sm font-medium">
                                                                {dayjs(selectedLog.finishTime).format('YYYY-MM-DD HH:mm:ss')}
                                                            </p>
                                                        </div>
                                                    </div>
                                                )}

                                                <div className="flex items-start gap-3">
                                                    <Timer className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                    <div className="flex-1">
                                                        <p className="text-xs text-muted-foreground mb-1">执行耗时</p>
                                                        <p className="text-sm font-medium font-mono">
                                                            {formatDuration(selectedLog.duration)}
                                                        </p>
                                                    </div>
                                                </div>

                                                {selectedLog.serverIp && (
                                                    <div className="flex items-start gap-3">
                                                        <Server className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                        <div className="flex-1">
                                                            <p className="text-xs text-muted-foreground mb-1">服务器信息</p>
                                                            <p className="text-sm font-medium font-mono">{selectedLog.serverIp}</p>
                                                            {selectedLog.serverHost && (
                                                                <p className="text-xs text-muted-foreground mt-1">{selectedLog.serverHost}</p>
                                                            )}
                                                        </div>
                                                    </div>
                                                )}
                                            </div>

                                            <Separator />

                                            {/* 技术信息 */}
                                            <div className="space-y-3">
                                                <div className="flex items-start gap-3">
                                                    <Code className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                    <div className="flex-1">
                                                        <p className="text-xs text-muted-foreground mb-1">Bean名称</p>
                                                        <code className="text-xs bg-muted px-2 py-1 rounded block overflow-x-auto">
                                                            {selectedLog.beanName}
                                                        </code>
                                                    </div>
                                                </div>

                                                <div className="flex items-start gap-3">
                                                    <Activity className="h-4 w-4 text-muted-foreground mt-0.5" />
                                                    <div className="flex-1">
                                                        <p className="text-xs text-muted-foreground mb-1">方法名称</p>
                                                        <code className="text-xs bg-muted px-2 py-1 rounded block overflow-x-auto">
                                                            {selectedLog.methodName}
                                                        </code>
                                                    </div>
                                                </div>

                                                {selectedLog.methodParams && (
                                                    <div>
                                                        <p className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                                                            <Code className="h-3.5 w-3.5" />
                                                            方法参数
                                                        </p>
                                                        <pre className="text-xs bg-muted p-3 rounded overflow-x-auto font-mono">
                                                            {selectedLog.methodParams}
                                                        </pre>
                                                    </div>
                                                )}
                                            </div>

                                            {/* 结果信息 */}
                                            {selectedLog.resultMessage && (
                                                <>
                                                    <Separator />
                                                    <div>
                                                        <p className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                                                            <CheckCircle2 className="h-3.5 w-3.5" />
                                                            结果消息
                                                        </p>
                                                        <div className="text-sm bg-muted/50 p-3 rounded border">
                                                            {selectedLog.resultMessage}
                                                        </div>
                                                    </div>
                                                </>
                                            )}

                                            {/* 异常信息 */}
                                            {selectedLog.exceptionInfo && (
                                                <>
                                                    <Separator />
                                                    <div>
                                                        <p className="text-xs text-destructive mb-2 flex items-center gap-1 font-medium">
                                                            <XCircle className="h-3.5 w-3.5" />
                                                            异常信息
                                                        </p>
                                                        <pre className="text-xs bg-destructive/5 border border-destructive/20 p-3 rounded overflow-x-auto font-mono text-destructive max-h-60">
                                                            {selectedLog.exceptionInfo}
                                                        </pre>
                                                    </div>
                                                </>
                                            )}
                                        </div>
                                    </ScrollArea>
                                ) : (
                                    <div className="flex items-center justify-center h-[556px] text-center">
                                        <div>
                                            <Info className="h-12 w-12 mx-auto mb-3 text-muted-foreground/30" />
                                            <p className="text-sm text-muted-foreground">
                                                选择左侧日志查看详情
                                            </p>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    ) : (
                        <div className="flex items-center justify-center h-64 border rounded-lg">
                            <div className="text-center">
                                <AlertCircle className="h-12 w-12 mx-auto mb-3 text-muted-foreground/30" />
                                <p className="text-sm text-muted-foreground">暂无执行日志</p>
                            </div>
                        </div>
                    )}
                </DialogBody>
            </DialogContent>
        </Dialog>
    );
};

export default JobLogDialog;

