import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
    Activity,
    CheckCircle2,
    XCircle,
    Pause,
    Clock,
    Loader2,
    TrendingUp,
    AlertCircle,
    Calendar,
} from 'lucide-react';
import { getDashboard, getScheduleJobs } from '../service';
import type { DashboardResponse, ScheduleJobResponse, LogStatus } from '../types';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import duration from 'dayjs/plugin/duration';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.extend(duration);
dayjs.locale('zh-cn');

const Dashboard: React.FC = () => {
    const [data, setData] = useState<DashboardResponse | null>(null);
    const [allJobs, setAllJobs] = useState<ScheduleJobResponse[]>([]);
    const [loading, setLoading] = useState(true);
    const [currentTime, setCurrentTime] = useState(dayjs());

    // 加载仪表盘数据
    const loadData = async () => {
        try {
            const [dashboardData, jobsData] = await Promise.all([
                getDashboard(),
                getScheduleJobs({ pageNum: 0, pageSize: 100 })
            ]);
            setData(dashboardData);
            setAllJobs(jobsData?.content || []);
        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
        } finally {
            setLoading(false);
        }
    };

    // 初始加载和5秒轮询
    useEffect(() => {
        loadData();
        const interval = setInterval(loadData, 5000);
        return () => clearInterval(interval);
    }, []);

    // 实时更新当前时间（用于倒计时）
    useEffect(() => {
        const timer = setInterval(() => {
            setCurrentTime(dayjs());
        }, 1000);
        return () => clearInterval(timer);
    }, []);

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

    // 按状态分组任务
    const groupedJobs = React.useMemo(() => {
        return {
            running: allJobs.filter(j => data?.runningJobs.some(r => r.jobId === j.id)),
            paused: allJobs.filter(j => j.status === 'PAUSED'),
            idle: allJobs.filter(j => j.status === 'ENABLED' && !data?.runningJobs.some(r => r.jobId === j.id)),
            disabled: allJobs.filter(j => j.status === 'DISABLED'),
        };
    }, [allJobs, data]);

    // 获取即将执行的任务（按下次执行时间排序）
    const upcomingJobs = React.useMemo(() => {
        return allJobs
            .filter(j => j.nextExecuteTime && j.status === 'ENABLED')
            .sort((a, b) => {
                if (!a.nextExecuteTime || !b.nextExecuteTime) return 0;
                return dayjs(a.nextExecuteTime).valueOf() - dayjs(b.nextExecuteTime).valueOf();
            })
            .slice(0, 10);
    }, [allJobs]);

    // 格式化倒计时
    const formatCountdown = (nextTime: string) => {
        const diff = dayjs(nextTime).diff(currentTime);
        if (diff <= 0) return '即将执行';
        const dur = dayjs.duration(diff);
        const days = dur.days();
        const hours = dur.hours();
        const minutes = dur.minutes();
        const seconds = dur.seconds();

        if (days > 0) return `${days}天${hours}小时后`;
        if (hours > 0) return `${hours}小时${minutes}分后`;
        if (minutes > 0) return `${minutes}分${seconds}秒后`;
        return `${seconds}秒后`;
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-96">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full space-y-4">
            {/* 任务概览统计卡片 */}
            <div className="grid gap-4 md:grid-cols-5 flex-shrink-0">
                <Card className="border-l-4 border-l-blue-500">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">任务总数</CardTitle>
                        <Activity className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{data?.summary.total || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">所有定时任务</p>
                    </CardContent>
                </Card>

                <Card className="border-l-4 border-l-orange-500">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">正在执行</CardTitle>
                        {data?.summary.running && data.summary.running > 0 ? (
                            <Loader2 className="h-4 w-4 text-orange-500 animate-spin" />
                        ) : (
                            <Activity className="h-4 w-4 text-muted-foreground" />
                        )}
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{data?.summary.running || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">运行中的任务</p>
                    </CardContent>
                </Card>

                <Card className="border-l-4 border-l-green-500">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">已启用</CardTitle>
                        <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{data?.summary.enabled || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">活跃的任务</p>
                    </CardContent>
                </Card>

                <Card className="border-l-4 border-l-yellow-500">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">已暂停</CardTitle>
                        <Pause className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{data?.summary.paused || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">暂停的任务</p>
                    </CardContent>
                </Card>

                <Card className="border-l-4 border-l-gray-500">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">已禁用</CardTitle>
                        <XCircle className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{data?.summary.disabled || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">停用的任务</p>
                    </CardContent>
                </Card>
            </div>

            {/* 多视图 Tabs */}
            <Tabs defaultValue="timeline" className="flex-1 flex flex-col min-h-0">
                <TabsList className="grid w-full grid-cols-3 flex-shrink-0">
                    <TabsTrigger value="timeline">
                        <Calendar className="h-4 w-4 mr-2" />
                        时间线视图
                    </TabsTrigger>
                    <TabsTrigger value="status">
                        <TrendingUp className="h-4 w-4 mr-2" />
                        状态分组
                    </TabsTrigger>
                    <TabsTrigger value="logs">
                        <AlertCircle className="h-4 w-4 mr-2" />
                        最近日志
                    </TabsTrigger>
                </TabsList>

                {/* 时间线视图 */}
                <TabsContent value="timeline" className="flex-1 min-h-0 mt-4">
                    <Card className="h-full flex flex-col">
                        <CardHeader className="flex-shrink-0">
                            <CardTitle>任务执行时间线</CardTitle>
                            <p className="text-sm text-muted-foreground">
                                即将执行的任务按时间顺序排列
                            </p>
                        </CardHeader>
                        <CardContent className="flex-1 min-h-0 overflow-hidden">
                            <ScrollArea className="h-full">
                                {upcomingJobs.length === 0 ? (
                                    <div className="text-center py-8 text-muted-foreground">
                                        <Clock className="h-12 w-12 mx-auto mb-2 opacity-20" />
                                        <p>暂无即将执行的任务</p>
                                    </div>
                                ) : (
                                    <div className="relative pl-8 pr-4">
                                    {/* 时间线 */}
                                    <div className="absolute left-3 top-0 bottom-0 w-0.5 bg-border" />
                                    
                                    {upcomingJobs.map((job, index) => (
                                        <div key={job.id} className="relative mb-6 last:mb-0">
                                            {/* 时间点 */}
                                            <div className="absolute -left-[1.65rem] top-1.5 w-3 h-3 rounded-full bg-primary border-2 border-background" />
                                            
                                            <div className="flex items-start gap-3">
                                                <div className="min-w-[80px] text-sm font-medium text-muted-foreground">
                                                    {dayjs(job.nextExecuteTime).format('HH:mm')}
                                                </div>
                                                <div className="flex-1 p-3 border rounded-lg hover:bg-accent transition-colors">
                                                    <div className="flex items-center justify-between">
                                                        <div>
                                                            <p className="font-medium">{job.jobName}</p>
                                                            <p className="text-sm text-muted-foreground mt-1">
                                                                {dayjs(job.nextExecuteTime).fromNow()}
                                                            </p>
                                                        </div>
                                                        <Badge variant="outline">
                                                            {index === 0 && data?.runningJobs.some(r => r.jobId === job.id) ? (
                                                                <span className="flex items-center gap-1">
                                                                    <Loader2 className="h-3 w-3 animate-spin" />
                                                                    执行中
                                                                </span>
                                                            ) : (
                                                                <span className="flex items-center gap-1">
                                                                    <Clock className="h-3 w-3" />
                                                                    待执行
                                                                </span>
                                                            )}
                                                        </Badge>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                    </div>
                                )}
                            </ScrollArea>
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* 状态分组视图 */}
                <TabsContent value="status" className="flex-1 min-h-0 mt-4">
                    <div className="grid gap-4 md:grid-cols-4 h-full">
                        {/* 运行中 */}
                        <Card className="border-l-4 border-l-orange-500 flex flex-col">
                            <CardHeader className="pb-3 flex-shrink-0">
                                <CardTitle className="text-sm flex items-center gap-2">
                                    <div className="h-2 w-2 rounded-full bg-orange-500 animate-pulse" />
                                    运行中
                                </CardTitle>
                                <div className="text-2xl font-bold">{groupedJobs.running.length}</div>
                            </CardHeader>
                            <CardContent className="flex-1 overflow-hidden">
                                <ScrollArea className="h-full pr-3">
                                    {groupedJobs.running.length === 0 ? (
                                        <div className="text-center py-8 text-muted-foreground text-sm">
                                            <Loader2 className="h-8 w-8 mx-auto mb-2 opacity-20" />
                                            <p>无正在运行的任务</p>
                                        </div>
                                    ) : (
                                        <div className="space-y-3">
                                            {groupedJobs.running.map((job) => {
                                                const runningJob = data?.runningJobs.find(r => r.jobId === job.id);
                                                return (
                                                    <div key={job.id} className="p-3 border rounded-lg bg-card hover:bg-accent transition-colors">
                                                        <p className="font-medium text-sm mb-2 truncate" title={job.jobName}>
                                                            {job.jobName}
                                                        </p>
                                                        {runningJob && (
                                                            <>
                                                                <Progress value={runningJob.progress} className="h-2 mb-2" />
                                                                <div className="flex items-center justify-between text-xs text-muted-foreground">
                                                                    <span>{runningJob.message || '执行中...'}</span>
                                                                    <Badge variant="outline" className="text-xs">
                                                                        {runningJob.progress}%
                                                                    </Badge>
                                                                </div>
                                                            </>
                                                        )}
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    )}
                                </ScrollArea>
                            </CardContent>
                        </Card>

                        {/* 已暂停 */}
                        <Card className="border-l-4 border-l-yellow-500 flex flex-col">
                            <CardHeader className="pb-3 flex-shrink-0">
                                <CardTitle className="text-sm flex items-center gap-2">
                                    <Pause className="h-4 w-4 text-yellow-600" />
                                    已暂停
                                </CardTitle>
                                <div className="text-2xl font-bold">{groupedJobs.paused.length}</div>
                            </CardHeader>
                            <CardContent className="flex-1 overflow-hidden">
                                <ScrollArea className="h-full pr-3">
                                    {groupedJobs.paused.length === 0 ? (
                                        <div className="text-center py-8 text-muted-foreground text-sm">
                                            <Pause className="h-8 w-8 mx-auto mb-2 opacity-20" />
                                            <p>无暂停的任务</p>
                                        </div>
                                    ) : (
                                        <div className="space-y-2">
                                            {groupedJobs.paused.map((job) => (
                                                <div key={job.id} className="p-3 border rounded-lg bg-card hover:bg-accent transition-colors">
                                                    <p className="font-medium text-sm mb-1 truncate" title={job.jobName}>
                                                        {job.jobName}
                                                    </p>
                                                    <p className="text-xs text-muted-foreground">
                                                        上次: {job.lastExecuteTime ? dayjs(job.lastExecuteTime).fromNow() : '-'}
                                                    </p>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </ScrollArea>
                            </CardContent>
                        </Card>

                        {/* 空闲中 */}
                        <Card className="border-l-4 border-l-green-500 flex flex-col">
                            <CardHeader className="pb-3 flex-shrink-0">
                                <CardTitle className="text-sm flex items-center gap-2">
                                    <CheckCircle2 className="h-4 w-4 text-green-600" />
                                    空闲中
                                </CardTitle>
                                <div className="text-2xl font-bold">{groupedJobs.idle.length}</div>
                            </CardHeader>
                            <CardContent className="flex-1 overflow-hidden">
                                <ScrollArea className="h-full pr-3">
                                    {groupedJobs.idle.length === 0 ? (
                                        <div className="text-center py-8 text-muted-foreground text-sm">
                                            <CheckCircle2 className="h-8 w-8 mx-auto mb-2 opacity-20" />
                                            <p>无空闲任务</p>
                                        </div>
                                    ) : (
                                        <div className="space-y-2">
                                            {groupedJobs.idle.map((job) => (
                                                <div key={job.id} className="p-3 border rounded-lg bg-card hover:bg-accent transition-colors">
                                                    <p className="font-medium text-sm mb-1 truncate" title={job.jobName}>
                                                        {job.jobName}
                                                    </p>
                                                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                                                        <Clock className="h-3 w-3" />
                                                        {job.nextExecuteTime ? formatCountdown(job.nextExecuteTime) : '-'}
                                                    </p>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </ScrollArea>
                            </CardContent>
                        </Card>

                        {/* 已禁用 */}
                        <Card className="border-l-4 border-l-gray-400 flex flex-col">
                            <CardHeader className="pb-3 flex-shrink-0">
                                <CardTitle className="text-sm flex items-center gap-2">
                                    <XCircle className="h-4 w-4 text-gray-500" />
                                    已禁用
                                </CardTitle>
                                <div className="text-2xl font-bold">{groupedJobs.disabled.length}</div>
                            </CardHeader>
                            <CardContent className="flex-1 overflow-hidden">
                                <ScrollArea className="h-full pr-3">
                                    {groupedJobs.disabled.length === 0 ? (
                                        <div className="text-center py-8 text-muted-foreground text-sm">
                                            <XCircle className="h-8 w-8 mx-auto mb-2 opacity-20" />
                                            <p>无禁用的任务</p>
                                        </div>
                                    ) : (
                                        <div className="space-y-2">
                                            {groupedJobs.disabled.map((job) => (
                                                <div key={job.id} className="p-3 border rounded-lg bg-card hover:bg-accent transition-colors opacity-60">
                                                    <p className="font-medium text-sm mb-1 truncate" title={job.jobName}>
                                                        {job.jobName}
                                                    </p>
                                                    <p className="text-xs text-muted-foreground">已停用</p>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </ScrollArea>
                            </CardContent>
                        </Card>
                    </div>
                </TabsContent>

                {/* 最近日志 */}
                <TabsContent value="logs" className="flex-1 min-h-0 mt-4">
                    <Card className="h-full flex flex-col">
                        <CardHeader className="flex-shrink-0">
                            <CardTitle>最近执行日志 (10条)</CardTitle>
                        </CardHeader>
                        <CardContent className="flex-1 min-h-0 overflow-hidden">
                            <ScrollArea className="h-full">
                                {!data || data.recentLogs.length === 0 ? (
                                    <div className="text-center py-8 text-muted-foreground">
                                        <AlertCircle className="h-12 w-12 mx-auto mb-2 opacity-20" />
                                        <p>暂无执行日志</p>
                                    </div>
                                ) : (
                                    <div className="space-y-3 pr-4">
                                    {data.recentLogs.map((log) => (
                                        <div key={log.id} className="p-3 border rounded-lg hover:bg-accent transition-colors">
                                            <div className="flex items-start justify-between mb-2">
                                                <div>
                                                    <p className="font-medium">{log.jobName}</p>
                                                    <p className="text-sm text-muted-foreground">
                                                        {dayjs(log.executeTime).format('YYYY-MM-DD HH:mm:ss')}
                                                    </p>
                                                </div>
                                                {getLogStatusBadge(log.status)}
                                            </div>
                                            {log.resultMessage && (
                                                <p className="text-sm text-muted-foreground">
                                                    {log.resultMessage}
                                                </p>
                                            )}
                                            {log.exceptionInfo && (
                                                <p className="text-sm text-red-600 mt-1">
                                                    {log.exceptionInfo}
                                                </p>
                                            )}
                                        </div>
                                    ))}
                                    </div>
                                )}
                            </ScrollArea>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    );
};

export default Dashboard;

