import React, { useRef } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { BetaSchemaForm } from '@ant-design/pro-components';
import { convertJsonSchemaToColumns } from '@/utils/jsonSchemaUtils';
import { message } from 'antd';
import type { DeploymentConfig } from '@/pages/Deploy/Deployment/List/types';
import { deployApp } from '../service';
import { DeployAppBuildDTO } from '../types';

interface DeploymentFormModalProps {
    open: boolean;
    onClose: () => void;
    formSchema: any;
    deployConfig: DeploymentConfig;
}

const DeploymentFormModal: React.FC<DeploymentFormModalProps> = ({
    open,
    onClose,
    formSchema,
    deployConfig
}) => {
    const formRef = useRef<any>();

    const handleSubmit = async (values: any) => {
        try {
            const deployData: DeployAppBuildDTO = {
                buildType: deployConfig.buildType,
                languageType: deployConfig.languageType,
                formVariables: values,
                buildVariables: deployConfig.buildVariables,
                environmentId: deployConfig.environmentId,
                applicationId: deployConfig.application.id,
                workflowDefinitionId: deployConfig.publishedWorkflowDefinition?.id || 0
            };

            await deployApp(deployData);
            message.success('部署任务已提交');
            onClose();
        } catch (error) {
            message.error('部署失败：' + (error instanceof Error ? error.message : '未知错误'));
        }
    };

    const columns = convertJsonSchemaToColumns(formSchema);

    return (
        <Dialog open={open} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle>部署 {deployConfig.application.appName}</DialogTitle>
                </DialogHeader>
                <div className="py-4">
                    <BetaSchemaForm
                        formRef={formRef}
                        layoutType="Form"
                        columns={columns}
                        onFinish={handleSubmit}
                        submitter={false}
                    />
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={onClose}>
                        取消
                    </Button>
                    <Button onClick={() => formRef.current?.submit()}>
                        确定
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};

export default DeploymentFormModal; 