import React, {useState, useEffect} from 'react';
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Badge} from "@/components/ui/badge";
import {Progress} from "@/components/ui/progress";
import {Button} from "@/components/ui/button";
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs";
import {Input} from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {cn} from "@/lib/utils";
import {
    Clock,
    Search,
    Edit,
    Package,
    ChevronRight,
    CheckCircle,
    AlertTriangle,
    XCircle,
    Loader2,
    ServerCrash,
    Server
} from "lucide-react";
import {getEnvironmentList} from '@/pages/Deploy/Environment/List/service';
import {getDevelopmentLanguages} from '@/pages/Deploy/Application/List/service';
import {getDeploymentConfigPage} from '@/pages/Deploy/Deployment/List/service';
import type {Environment} from '@/pages/Deploy/Environment/List/types';
import type {DevelopmentLanguageType} from '@/pages/Deploy/Application/List/types';
import type {DeploymentConfig} from '@/pages/Deploy/Deployment/List/types';
import type {Page} from '@/types/base';
import type { JsonNode } from '@/types/common';
import DeploymentFormModal from './components/DeploymentFormModal';
import {message} from "antd";

type EnvironmentStatus = 'success' | 'warning' | 'error';

// 扩展环境类型，添加监控数据
interface EnhancedEnvironment extends Environment {
    projectCount: number;
    status: EnvironmentStatus;
    lastDeployment: string;
    cpu: number;
    memory: number;
    storage: number;
}

const EmptyState: React.FC<{ title: string; description: string; icon: React.ReactNode }> = ({
                                                                                                 title,
                                                                                                 description,
                                                                                                 icon
                                                                                             }) => (
    <div className="flex flex-col items-center justify-center p-8 text-center">
        <div className="rounded-full bg-muted p-3 mb-4">
            {icon}
        </div>
        <h3 className="text-lg font-semibold mb-2">{title}</h3>
        <p className="text-sm text-muted-foreground max-w-sm">{description}</p>
    </div>
);

const LoadingState = () => (
    <div className="flex-1 p-8">
        <div className="flex flex-col items-center justify-center min-h-[400px]">
            <Loader2 className="h-8 w-8 animate-spin text-primary mb-4"/>
            <p className="text-sm text-muted-foreground">加载中，请稍候...</p>
        </div>
    </div>
);

const Dashboard: React.FC = () => {
    const [projectType, setProjectType] = useState("ALL");
    const [status, setStatus] = useState("");
    const [environments, setEnvironments] = useState<EnhancedEnvironment[]>([]);
    const [loading, setLoading] = useState(true);
    const [languages, setLanguages] = useState<DevelopmentLanguageType[]>([]);
    const [deployConfigs, setDeployConfigs] = useState<DeploymentConfig[]>([]);
    const [searchText, setSearchText] = useState("");
    const [currentEnvId, setCurrentEnvId] = useState<number>();
    const [deployModalOpen, setDeployModalOpen] = useState(false);
    const [selectedConfig, setSelectedConfig] = useState<DeploymentConfig | null>(null);

    // 获取环境和语言数据
    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const [envResponse, langResponse] = await Promise.all([
                    getEnvironmentList(),
                    getDevelopmentLanguages()
                ]);

                if (envResponse) {
                    const enrichedEnvironments = envResponse.map(env => {
                        const randomStatus: EnvironmentStatus = Math.random() > 0.7 ? 'warning' : 'success';
                        return {
                            ...env,
                            projectCount: 0, // 初始化为0，后续更新
                            status: randomStatus,
                            lastDeployment: '暂无部署',
                            cpu: Math.floor(Math.random() * 40) + 40,
                            memory: Math.floor(Math.random() * 30) + 50,
                            storage: Math.floor(Math.random() * 40) + 30,
                        };
                    });
                    setEnvironments(enrichedEnvironments);
                    if (enrichedEnvironments.length > 0) {
                        setCurrentEnvId(enrichedEnvironments[0].id);
                    }
                }

                if (langResponse) {
                    setLanguages(langResponse);
                }
            } catch (error) {
                console.error('Failed to fetch data:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    // 获取部署配置数据
    useEffect(() => {
        const fetchDeployConfigs = async () => {
            if (!currentEnvId) return;

            try {
                const response = await getDeploymentConfigPage({
                    pageSize: 100,
                    pageNum: 1,
                    environmentId: currentEnvId,
                    workflowDefinitionId: 0,
                    enabled: undefined
                });

                if (response) {
                    setDeployConfigs(response.content);
                    // 更新环境的项目数量
                    setEnvironments(prevEnvs =>
                        prevEnvs.map(env =>
                            env.id === currentEnvId
                                ? {...env, projectCount: response.totalElements}
                                : env
                        )
                    );
                }
            } catch (error) {
                console.error('Failed to fetch deployment configs:', error);
            }
        };

        fetchDeployConfigs();
    }, [currentEnvId]);

    const handleSearch = async () => {
        if (!currentEnvId) return;

        try {
            const params: any = {
                pageSize: 100,
                pageNum: 1,
                environmentId: currentEnvId,
                enabled: status === 'active' ? true : status === 'paused' ? false : undefined
            };

            // 如果选择了具体语言（不是"所有"），添加到查询参数
            if (projectType !== 'ALL') {
                params.languageType = projectType;
            }

            const response = await getDeploymentConfigPage(params);

            if (response) {
                setDeployConfigs(response.content);
            }
        } catch (error) {
            console.error('Failed to search deployment configs:', error);
        }
    };

    const handleReset = () => {
        setSearchText("");
        setProjectType("ALL");
        setStatus("");
        if (currentEnvId) {
            getDeploymentConfigPage({
                pageSize: 100,
                pageNum: 1,
                environmentId: currentEnvId,
                workflowDefinitionId: 0,
                enabled: undefined
            }).then(response => {
                if (response) {
                    setDeployConfigs(response.content);
                }
            });
        }
    };

    const handleTabChange = (envCode: string) => {
        const env = environments.find(e => e.envCode === envCode);
        if (env) {
            setCurrentEnvId(env.id);
        }
    };

    const getStatusIcon = (status: string) => {
        switch (status) {
            case 'success':
                return <CheckCircle className="h-5 w-5 text-green-500"/>;
            case 'warning':
                return <AlertTriangle className="h-5 w-5 text-yellow-500"/>;
            case 'error':
                return <XCircle className="h-5 w-5 text-red-500"/>;
            default:
                return <Clock className="h-5 w-5 text-blue-500"/>;
        }
    };

    const getBuildStatusBadge = (enabled: boolean) => {
        const config = enabled
            ? {className: "bg-green-100 text-green-800", text: "活跃"}
            : {className: "bg-red-100 text-red-800", text: "暂停"};

        return (
            <Badge className={cn("rounded-full", config.className)}>
                {config.text}
            </Badge>
        );
    };

    const handleDeploy = (config: DeploymentConfig) => {
        if (!config?.formVariablesSchema) {
            message.error('工作流配置有误，请检查工作流定义');
            return;
        }
        setSelectedConfig(config);
        setDeployModalOpen(true);
    };

    if (loading) {
        return <LoadingState/>;
    }

    const hasEnvironments = environments.length > 0;
    const hasProjects = deployConfigs.length > 0;

    return (
        <div className="flex-1 p-8">
            <h2 className="text-2xl font-semibold mb-6">部署环境概览</h2>

            {!hasEnvironments ? (
                <Card>
                    <CardContent>
                        <EmptyState
                            icon={<ServerCrash className="h-8 w-8 text-muted-foreground"/>}
                            title="暂无环境数据"
                            description="当前系统中还没有配置任何环境。请先添加部署环境，然后开始使用部署功能。"
                        />
                    </CardContent>
                </Card>
            ) : (
                <>

                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                        {environments.map((env) => (
                            <Card key={env.id} className="hover:shadow-lg transition-shadow duration-300">
                                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                    <CardTitle className="text-sm font-medium">{env.envName}</CardTitle>
                                    {getStatusIcon(env.status)}
                                </CardHeader>
                                <CardContent>
                                    <div className="text-2xl font-bold">{env.projectCount}</div>
                                    <p className="text-xs text-muted-foreground">个项目</p>
                                    <div className="mt-4 space-y-2">
                                        <div className="flex items-center text-sm">
                                            <Clock className="mr-2 h-4 w-4 text-muted-foreground"/>
                                            最近部署: {env.lastDeployment}
                                        </div>
                                        <div className="space-y-1">
                                            <div className="flex justify-between text-xs">
                                                <span>CPU</span>
                                                <span>{env.cpu}%</span>
                                            </div>
                                            <Progress value={env.cpu} className="h-1"/>
                                        </div>
                                        <div className="space-y-1">
                                            <div className="flex justify-between text-xs">
                                                <span>内存</span>
                                                <span>{env.memory}%</span>
                                            </div>
                                            <Progress value={env.memory} className="h-1"/>
                                        </div>
                                        <div className="space-y-1">
                                            <div className="flex justify-between text-xs">
                                                <span>存储</span>
                                                <span>{env.storage}%</span>
                                            </div>
                                            <Progress value={env.storage} className="h-1"/>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>

                    <div className="bg-white rounded-lg shadow">
                        <Tabs
                            defaultValue={environments[0]?.envCode}
                            className="w-full"
                            onValueChange={handleTabChange}
                        >
                            <div className="border-b px-6">
                                <TabsList className="h-16">
                                    {environments.map((env) => (
                                        <TabsTrigger
                                            key={env.id}
                                            value={env.envCode}
                                            className="px-6 py-3 data-[state=active]:border-b-2 data-[state=active]:border-blue-600"
                                        >
                                            {env.envName}
                                        </TabsTrigger>
                                    ))}
                                </TabsList>
                            </div>

                            {environments.map((env) => (
                                <TabsContent key={env.id} value={env.envCode} className="p-6">
                                    <div className="mb-6">
                                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                                            <Input
                                                placeholder="项目名称或代码"
                                                value={searchText}
                                                onChange={(e) => setSearchText(e.target.value)}
                                            />
                                            <Select value={projectType} onValueChange={setProjectType}>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="开发语言"/>
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="ALL">所有</SelectItem>
                                                    {languages.map(lang => (
                                                        <SelectItem key={lang.code} value={lang.code}>
                                                            {lang.name}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <Select value={status} onValueChange={setStatus}>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="项目状态"/>
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="active">活跃</SelectItem>
                                                    <SelectItem value="paused">暂停</SelectItem>
                                                </SelectContent>
                                            </Select>
                                            <div className="flex space-x-2">
                                                <Button className="flex-1" onClick={handleSearch}>
                                                    <Search className="w-4 h-4 mr-2"/>
                                                    搜索
                                                </Button>
                                                <Button variant="outline" className="flex-1" onClick={handleReset}>
                                                    重置
                                                </Button>
                                            </div>
                                        </div>
                                    </div>

                                    {!hasProjects ? (
                                        <Card>
                                            <CardContent>
                                                <EmptyState
                                                    icon={<Server className="h-8 w-8 text-muted-foreground"/>}
                                                    title="暂无项目数据"
                                                    description="当前环境中还没有配置任何项目。请先创建项目，然后开始部署。"
                                                />
                                            </CardContent>
                                        </Card>
                                    ) : (
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                            {deployConfigs.map((config) => (
                                                <Card key={config.id} className="hover:shadow-md transition-shadow duration-300">
                                                    <CardContent className="p-4">
                                                        <div className="flex justify-between items-start mb-2">
                                                            <div>
                                                                <h3 className="text-lg font-semibold">{config.application.appName}</h3>
                                                                <p className="text-sm text-gray-500">{config.application.appCode}</p>
                                                            </div>
                                                            {getBuildStatusBadge(config.enabled)}
                                                        </div>
                                                        <div className="grid grid-cols-2 gap-2 text-sm mb-4">
                                                            <div>
                                                                <p className="text-gray-500">构建类型</p>
                                                                <p className="font-medium">{config.buildType}</p>
                                                            </div>
                                                            <div>
                                                                <p className="text-gray-500">开发语言</p>
                                                                <p className="font-medium">{config.languageType}</p>
                                                            </div>
                                                            <div>
                                                                <p className="text-gray-500">工作流</p>
                                                                <p className="font-medium">{config.publishedWorkflowDefinition?.name || '未配置'}</p>
                                                            </div>
                                                            <div>
                                                                <p className="text-gray-500">最后部署时间</p>
                                                                <p className="font-medium">{config.lastBuildStartTime ? new Date(config.lastBuildStartTime).toLocaleString() : '暂无部署'}</p>
                                                            </div>
                                                        </div>
                                                        <div className="border-t pt-2 mt-2">
                                                            <div className="grid grid-cols-2 gap-2 text-sm">
                                                                <div>
                                                                    <p className="text-gray-500">构建状态</p>
                                                                    <p className={cn(
                                                                        "font-medium",
                                                                        config.lastBuildStatus === 'COMPLETED' ? 'text-green-600' :
                                                                        config.lastBuildStatus === 'FAILED' ? 'text-red-600' :
                                                                        config.lastBuildStatus === 'RUNNING' ? 'text-blue-600' : 'text-gray-600'
                                                                    )}>
                                                                        {config.lastBuildStatus === 'COMPLETED' ? '构建成功' :
                                                                         config.lastBuildStatus === 'FAILED' ? '构建失败' :
                                                                         config.lastBuildStatus === 'RUNNING' ? '构建中' : '未构建'}
                                                                    </p>
                                                                </div>
                                                                <div>
                                                                    <p className="text-gray-500">构建时长</p>
                                                                    <p className="font-medium">
                                                                        {config.lastBuildStartTime && config.lastBuildEndTime ? (
                                                                            `${Math.round((new Date(config.lastBuildEndTime).getTime() - new Date(config.lastBuildStartTime).getTime()) / 1000 / 60)} 分钟`
                                                                        ) : '暂无数据'}
                                                                    </p>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div className="flex justify-end space-x-2 mt-4">
                                                            <Button variant="outline" size="sm" onClick={() => handleDeploy(config)}>
                                                                <Package className="h-4 w-4 mr-1"/>
                                                                部署
                                                            </Button>
                                                            <Button variant="outline" size="sm">
                                                                <ChevronRight className="h-4 w-4"/>
                                                                详情
                                                            </Button>
                                                        </div>
                                                    </CardContent>
                                                </Card>
                                            ))}
                                        </div>
                                    )}
                                </TabsContent>
                            ))}
                        </Tabs>
                    </div>
                </>

            )}
            {selectedConfig && selectedConfig.formVariablesSchema && (
                <DeploymentFormModal
                    open={deployModalOpen}
                    onClose={() => {
                        setDeployModalOpen(false);
                        setSelectedConfig(null);
                    }}
                    formSchema={selectedConfig.formVariablesSchema}
                    deployConfig={selectedConfig}
                />
            )}
        </div>
    );
};

export default Dashboard; 