import React, { useEffect, useCallback } from 'react';
import { Card, CardContent } from "@/components/ui/card";
import { Package, Server } from "lucide-react";
import { TeamSelector } from './components/TeamSelector';
import { EnvironmentTabs } from './components/EnvironmentTabs';
import { PendingApprovalModal } from './components/PendingApprovalModal';
import { useDeploymentData } from './hooks/useDeploymentData';
import { usePendingApproval } from './hooks/usePendingApproval';
import type { ApplicationConfig } from './types';

// ✅ 优化：使用骨架屏替代 loading，体验更好
const LoadingState = () => (
    <div className="flex-1 p-8 space-y-6">
        {/* 标题骨架 */}
        <div className="space-y-2">
            <div className="h-9 w-48 bg-slate-200 rounded animate-pulse" />
            <div className="h-5 w-64 bg-slate-100 rounded animate-pulse" />
        </div>
        
        {/* 卡片骨架 */}
        <div className="space-y-4">
            <div className="h-12 w-full bg-slate-100 rounded animate-pulse" />
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                {[1, 2, 3, 4].map((i) => (
                    <div key={i} className="h-48 bg-slate-100 rounded-lg animate-pulse" />
                ))}
            </div>
        </div>
    </div>
);

/**
 * Dashboard 组件 - 优化版
 * 
 * 优化点:
 * 1. 拆分为更小的子组件（TeamSelector, EnvironmentTabs）
 * 2. 使用自定义 hooks 管理状态（useDeploymentData, usePendingApproval）
 * 3. 使用 React.memo 和 useCallback 优化性能
 * 4. 智能轮询 - 根据部署状态动态调整轮询频率
 */
const Dashboard: React.FC = () => {
    // 使用自定义 hooks 管理状态
    const deploymentData = useDeploymentData({
        onInitialLoadComplete: () => {
            // 初始加载完成后，加载待审批数据
            approvalData.loadPendingApprovalCount();
        }
    });

    const approvalData = usePendingApproval({
        teams: deploymentData.teams,
        currentTeamId: deploymentData.currentTeamId,
        currentEnvId: deploymentData.currentEnvId,
        pollingEnabled: !deploymentData.loading
    });

    // 监听团队数据变化，自动刷新待审批数量
    useEffect(() => {
        if (deploymentData.teams.length > 0) {
            approvalData.loadPendingApprovalCount();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [deploymentData.teams.length]);

    // 监听团队/环境切换，自动刷新待审批数量
    useEffect(() => {
        if (deploymentData.currentTeamId && deploymentData.currentEnvId) {
            approvalData.loadPendingApprovalCount();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [deploymentData.currentTeamId, deploymentData.currentEnvId]);

    // 计算当前环境是否应该显示待审批按钮
    // 逻辑：当前环境需要审批 且 用户是该环境的审批人
    const shouldShowApprovalButton = React.useMemo(() => {
        if (!deploymentData.currentTeam || !deploymentData.currentEnvId) {
            return false;
        }
        const currentEnv = deploymentData.currentTeam.environments.find(
            env => env.environmentId === deploymentData.currentEnvId
        );
        return currentEnv?.requiresApproval === true && currentEnv?.canApprove === true;
    }, [deploymentData.currentTeam, deploymentData.currentEnvId]);

    // 处理部署成功 - 使用 useCallback 避免重复创建
    const handleDeploy = useCallback(async (app: ApplicationConfig, remark: string) => {
        await deploymentData.handleDeploySuccess();
        await approvalData.refreshApprovalCount();
    }, [deploymentData.handleDeploySuccess, approvalData.refreshApprovalCount]);

    // 加载状态
    if (deploymentData.loading) {
        return <LoadingState/>;
    }

    // 无团队状态
    if (deploymentData.teams.length === 0) {
        return (
            <div className="flex-1 p-8">
                <h2 className="text-3xl font-bold tracking-tight mb-6">部署管理</h2>
                <Card>
                    <CardContent className="flex flex-col items-center justify-center py-12">
                        <Package className="h-12 w-12 text-muted-foreground mb-4" />
                        <p className="text-sm text-muted-foreground">您还没有加入任何团队</p>
                    </CardContent>
                </Card>
            </div>
        );
    }

    return (
        <div className="flex-1 p-8 space-y-6">
            {/* 页面标题和团队选择器 */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">部署管理</h2>
                    <p className="text-muted-foreground mt-1">
                        管理和执行应用部署任务
                    </p>
                </div>
                
                <TeamSelector
                    teams={deploymentData.teams}
                    currentTeamId={deploymentData.currentTeamId}
                    pendingApprovalCount={approvalData.pendingApprovalCount}
                    showApprovalButton={shouldShowApprovalButton}
                    onTeamChange={deploymentData.handleTeamChange}
                    onApprovalClick={() => approvalData.setApprovalModalOpen(true)}
                />
            </div>

            {/* 当前团队信息 */}
            {deploymentData.currentTeam && (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <span className="font-medium text-foreground">{deploymentData.currentTeam.teamName}</span>
                    {deploymentData.currentTeam.description && (
                        <>
                            <span>·</span>
                            <span>{deploymentData.currentTeam.description}</span>
                        </>
                    )}
                </div>
            )}

            {/* 环境切换和应用列表 */}
            {deploymentData.currentTeam && (
                deploymentData.currentTeam.environments.length === 0 ? (
                    <Card>
                        <CardContent className="flex flex-col items-center justify-center py-16">
                            <Server className="h-16 w-16 text-muted-foreground mb-4" />
                            <h3 className="text-lg font-semibold mb-2">暂无部署环境</h3>
                            <p className="text-sm text-muted-foreground">
                                当前团队「{deploymentData.currentTeam.teamName}」还没有配置任何部署环境
                            </p>
                        </CardContent>
                    </Card>
                ) : (
                    <EnvironmentTabs
                        team={deploymentData.currentTeam}
                        currentEnvId={deploymentData.currentEnvId}
                        deploying={deploymentData.deploying}
                        onEnvChange={deploymentData.setCurrentEnvId}
                        onDeploy={handleDeploy}
                    />
                )
            )}

            {/* 待审批列表弹窗 */}
            <PendingApprovalModal
                open={approvalData.approvalModalOpen}
                onOpenChange={approvalData.setApprovalModalOpen}
                workflowDefinitionKeys={approvalData.workflowDefinitionKeys}
                teamId={deploymentData.currentTeamId || undefined}
                environmentId={deploymentData.currentEnvId || undefined}
            />
        </div>
    );
};

export default Dashboard; 