import React, {useRef, useEffect, useState} from 'react';
import {useSelector} from 'react-redux';
import type {RootState} from '@/store';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogBody,
    DialogFooter,
} from "@/components/ui/dialog";
import {Button} from "@/components/ui/button";
import {message} from 'antd';
import {Loader2} from 'lucide-react';
import {FormRenderer, type FormRendererRef, type FormSchema} from '@/components/FormDesigner';
import {getDefinitionById} from '@/pages/Form/Definition/List/service';
import {startDeployment} from '../service';
import type {ApplicationConfig, DeployEnvironment} from '../types';

interface DeploymentFormModalProps {
    open: boolean;
    onClose: () => void;
    app: ApplicationConfig;
    environment: DeployEnvironment;
    teamId: number;
    onSuccess?: () => void;
}

const DeploymentFormModal: React.FC<DeploymentFormModalProps> = ({
                                                                     open,
                                                                     onClose,
                                                                     app,
                                                                     environment,
                                                                     teamId,
                                                                     onSuccess
                                                                 }) => {
    const formRef = useRef<FormRendererRef>(null);
    const [formSchema, setFormSchema] = useState<FormSchema | null>(null);
    const [loading, setLoading] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    
    // 获取当前登录用户
    const currentUser = useSelector((state: RootState) => state.user.userInfo);

    // 使用 useMemo 缓存预填充数据，避免每次渲染都创建新对象
    const prefillData = React.useMemo(() => {
        return {
            // 构建类型
            buildType: app.buildType || 'JENKINS',
            // Jenkins 配置（仅当 buildType 为 JENKINS 时需要）
            jenkins: app.buildType === 'JENKINS' ? {
                serverId: app.deploySystemId?.toString() || '',
                jobName: app.deployJob || '',
                branch: app.sourceBranch,
            } : undefined,
            // 源Git仓库配置
            sourceRepository: app.sourceGitSystemId ? {
                systemId: app.sourceGitSystemId,
                projectId: app.sourceGitProjectId,
                branch: app.sourceBranch,
            } : undefined,
            // 目标Git仓库配置
            targetRepository: app.targetGitSystemId ? {
                systemId: app.targetGitSystemId,
                projectId: app.targetGitProjectId,
                branch: app.targetBranch,
            } : undefined,
            // 团队信息
            teamId: teamId?.toString() || '',
            // 应用信息
            teamApplicationId: app.teamApplicationId?.toString() || '',
            applicationId: app.applicationId?.toString() || '',
            applicationCode: app.applicationCode || '',
            applicationName: app.applicationName || '',
            // 环境信息
            environmentId: environment.environmentId?.toString() || '',
            environmentCode: environment.environmentCode || '',
            environmentName: environment.environmentName || '',
            // 任务编号（自动生成）
            deployRemark: '',
            // 部署人（当前登录用户的 username）
            deployUser: currentUser?.username || '',
            // 审批信息
            approval: {
                required: environment.requiresApproval ? 'true' : 'false',
                userNames: environment.approvers?.map(a => a.username) || [],
            },
            // 通知信息（使用环境配置的通知设置）
            notification: {
                notificationChannelId: environment.notificationConfig?.notificationChannelId,
                preApprovalNotificationEnabled: environment.notificationConfig?.preApprovalNotificationEnabled,
                preApprovalNotificationTemplateId: environment.notificationConfig?.preApprovalNotificationTemplateId,
                buildNotificationEnabled: environment.notificationConfig?.buildNotificationEnabled,
                buildNotificationTemplateId: environment.notificationConfig?.buildNotificationTemplateId,
                buildFailureFileEnabled: environment.notificationConfig?.buildFailureFileEnabled,
            },
        };
    }, [app, environment, teamId, currentUser]); // 只在这些依赖变化时重新生成

    // 1. 加载表单定义 (ID=2)
    useEffect(() => {
        if (open) {
            loadFormSchema();
        }
    }, [open]);

    const loadFormSchema = async () => {
        try {
            setLoading(true);
            const formDefinition = await getDefinitionById(2); // 固定表单ID=2
            setFormSchema(formDefinition.schema);
        } catch (error) {
            console.error('❌ 加载表单定义失败:', error);
            message.error('加载表单失败');
        } finally {
            setLoading(false);
        }
    };


    // 2. beforeSubmit 钩子：合并预填充数据
    const handleBeforeSubmit = async (userInputData: Record<string, any>) => {
        // 合并数据：用户输入优先级更高
        const finalData = {
            ...prefillData,       // 预填充数据（底层）
            ...userInputData,     // 用户修改的数据（覆盖）
        };

        return finalData;
    };

    // 3. 提交到后端
    const handleSubmit = async (formData: Record<string, any>) => {
        try {
            // 开发环境下打印完整数据用于调试
            if (import.meta.env.DEV) {
                console.group('🚀 部署请求数据');
                console.log('完整数据结构:', JSON.stringify(formData, null, 2));
                console.log('数据对象:', formData);
                console.groupEnd();
            }

            // 使用完整的表单数据提交到后端
            await startDeployment(formData);

            message.success(
                environment.requiresApproval
                    ? '部署申请已提交，等待审批'
                    : '部署任务已创建'
            );

            return {success: true};
        } catch (error: any) {
            // 直接抛出原始错误，让 request.ts 拦截器统一处理错误提示
            throw error;
        }
    };

    // 4. 提交成功后的处理
    const handleAfterSubmit = async () => {
        onClose();
        if (onSuccess) {
            onSuccess();
        }
    };

    // 5. 错误处理
    const handleError = async (error: any) => {
        // 不再显示错误提示，因为 request.ts 拦截器已经统一处理了
        // 这里只做日志记录，避免重复提示
        console.error('部署失败:', error);
    };

    return (
        <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
            <DialogContent className="sm:max-w-[800px]">
                <DialogHeader>
                    <DialogTitle>
                        部署 {app.applicationName} 到 {environment.environmentName}
                    </DialogTitle>
                    <DialogDescription>
                        请填写部署配置信息并确认提交
                    </DialogDescription>
                </DialogHeader>

                <DialogBody className="max-h-[60vh]">
                    {loading ? (
                        <div className="flex items-center justify-center py-12">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground"/>
                            <span className="ml-2 text-muted-foreground">加载表单中...</span>
                        </div>
                    ) : formSchema ? (
                        <FormRenderer
                            ref={formRef}
                            schema={formSchema}
                            value={prefillData}
                            beforeSubmit={handleBeforeSubmit}
                            onSubmit={handleSubmit}
                            afterSubmit={handleAfterSubmit}
                            onError={handleError}
                        />
                    ) : (
                        <div className="text-center text-muted-foreground py-12">
                            表单加载失败，请稍后重试
                        </div>
                    )}
                </DialogBody>

                <DialogFooter>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={onClose}
                        disabled={submitLoading}
                    >
                        取消
                    </Button>
                    <Button
                        type="button"
                        disabled={submitLoading || loading}
                        onClick={async () => {
                            try {
                                setSubmitLoading(true);
                                await formRef.current?.submit();
                            } finally {
                                setSubmitLoading(false);
                            }
                        }}
                    >
                        {submitLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin"/>}
                        {submitLoading ? '提交中...' : '确认部署'}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};

export default DeploymentFormModal;
