import React, {useEffect, useState, useCallback} from 'react';
import {Modal, Form, Select, message, Switch, Space, Button} from 'antd';
import {FullscreenOutlined} from '@ant-design/icons';
import type {DeploymentConfig, DeployConfigTemplate, CreateDeploymentConfigRequest} from '../types';
import {createDeploymentConfig, updateDeploymentConfig, getDeployConfigTemplates} from '../service';
import {getApplicationList} from '../../../Application/List/service';
import type {Application} from '../../../Application/List/types';
import {BetaSchemaForm} from '@ant-design/pro-components';
import {convertJsonSchemaToColumns} from '@/utils/jsonSchemaUtils';
import {Editor} from '@/components/Editor';
import type {JsonNode} from '@/types/common';
import {getPublishedDefinitions} from '@/pages/Workflow/Definition/service';
import type {WorkflowDefinition} from '@/pages/Workflow/Definition/types';
import './styles.less';

const {Option} = Select;

interface DeploymentConfigModalProps {
    open: boolean;
    onCancel: () => void;
    onSuccess: () => void;
    initialValues?: DeploymentConfig;
    envId: number;
}

const DeploymentConfigModal: React.FC<DeploymentConfigModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
    envId,
}) => {
    const [form] = Form.useForm();
    const [applications, setApplications] = useState<Application[]>([]);
    const [templates, setTemplates] = useState<DeployConfigTemplate[]>([]);
    const [selectedTemplate, setSelectedTemplate] = useState<DeployConfigTemplate>();
    const [buildVariables, setBuildVariables] = useState<JsonNode>({});
    const [loading, setLoading] = useState(false);
    const [workflowDefinitions, setWorkflowDefinitions] = useState<WorkflowDefinition[]>([]);
    const [fullscreenEditor, setFullscreenEditor] = useState<{
        key: string;
        title: string;
    } | null>(null);
    const isEdit = !!initialValues?.id;

    // 获取应用列表
    const fetchApplications = useCallback(async () => {
        try {
            const data = await getApplicationList();
            setApplications(data);
        } catch (error) {
            message.error('获取应用列表失败');
        }
    }, []);

    // 获取配置模板
    const fetchTemplates = useCallback(async () => {
        try {
            const data = await getDeployConfigTemplates();
            setTemplates(data);
        } catch (error) {
            message.error('获取配置模板失败');
        }
    }, []);

    // 获取已发布的工作流列表
    const fetchWorkflowDefinitions = useCallback(async () => {
        try {
            const data = await getPublishedDefinitions(0);
            setWorkflowDefinitions(data);
        } catch (error) {
            message.error('获取工作流列表失败');
        }
    }, []);

    // 在模态框显示时获取数据
    useEffect(() => {
        if (open) {
            fetchApplications();
            fetchTemplates();
            if (!isEdit) {
                fetchWorkflowDefinitions();
            }
        }
    }, [open, fetchApplications, fetchTemplates, fetchWorkflowDefinitions, isEdit]);

    // 初始化表单数据
    useEffect(() => {
        if (!open) return;

        if (initialValues) {
            // 设置基础字段
            form.setFieldsValue({
                applicationId: initialValues.applicationId,
                enabled: initialValues.enabled,
                ...initialValues.buildVariables  // 设置所有构建变量到表单中
            });

            const template = templates.find(t => t.buildType === initialValues.buildType && t.languageType === initialValues.languageType);
            if (template) {
                setSelectedTemplate(template);
                // 只保存编辑器字段的值到 buildVariables
                const editorValues = Object.entries(initialValues.buildVariables || {})
                    .filter(([key]) => template.buildVariablesSchema?.properties?.[key]?.editorConfig)
                    .reduce((acc, [key, value]) => ({...acc, [key]: value}), {});
                setBuildVariables(editorValues);
            }
        } else {
            form.resetFields();
            form.setFieldsValue({
                enabled: true
            });
            setSelectedTemplate(undefined);
            setBuildVariables({});
        }
    }, [open, initialValues, form, templates]);

    const handleAppChange = useCallback((applicationId: number) => {
        const app = applications.find(a => a.id === applicationId);
        if (app) {
            const template = templates.find(t => t.languageType === app.language);
            if (template) {
                setSelectedTemplate(template);
                setBuildVariables({});
                // 重置除了 applicationId 和 enabled 之外的所有字段
                const currentValues = form.getFieldsValue();
                form.setFieldsValue({
                    applicationId: currentValues.applicationId,
                    enabled: currentValues.enabled
                });
            }
        }
    }, [applications, templates, form]);

    const handleFormValuesChange = (changedValues: Record<string, any>) => {
        setBuildVariables(prev => ({
            ...prev,
            ...changedValues
        }));
    };

    const handleSubmit = async () => {
        try {
            setLoading(true);
            const formValues = await form.validateFields();

            // 获取选中的应用信息
            const selectedApp = applications.find(app => app.id === formValues.applicationId);
            if (!selectedApp) {
                throw new Error('请选择应用');
            }

            // 获取对应的模板
            const template = templates.find(t => t.languageType === selectedApp.language);
            if (!template) {
                throw new Error('未找到匹配配置模板');
            }

            // 从 formValues 中提取构建变量（排除 applicationId、enabled 和 workflowDefinitionId）
            const { applicationId, enabled, workflowDefinitionId, ...formBuildVariables } = formValues;

            // 构建提交数据
            const submitData: CreateDeploymentConfigRequest = {
                environmentId: envId,
                applicationId,
                buildType: template.buildType,
                languageType: selectedApp.language,
                buildVariables: {
                    ...formBuildVariables,  // 表单中的值
                    ...buildVariables  // 编辑器中的值
                } as Record<string, any>,  // 使用类型断言确保类型兼容
                enabled,
                workflowDefinitionId: isEdit ? initialValues.workflowDefinitionId : workflowDefinitionId
            };

            if (isEdit) {
                await updateDeploymentConfig({
                    ...submitData,
                    id: initialValues.id,
                    formVariablesSchema: initialValues.formVariablesSchema,
                });
            } else {
                await createDeploymentConfig(submitData);
            }
            message.success(`${isEdit ? '更新' : '创建'}成功`);
            form.resetFields();
            onSuccess();
        } catch (error) {
            if (error instanceof Error) {
                message.error(`${isEdit ? '更新' : '创建'}失败: ${error.message}`);
            } else {
                message.error(`${isEdit ? '更新' : '创建'}失败`);
            }
        } finally {
            setLoading(false);
        }
    };

    // 处理富文本编辑器的值变化
    const handleEditorChange = (key: string, value: string | undefined) => {
        setBuildVariables(prev => ({
            ...prev,
            [key]: value || ''
        }));
    };

    return (
        <>
            <Modal
                title={`${isEdit ? '编辑' : '新建'}部署配置`}
                open={open}
                onCancel={() => {
                    form.resetFields();
                    onCancel();
                }}
                onOk={handleSubmit}
                width={800}
                className="deployment-config-modal"
                maskClosable={false}
                confirmLoading={loading}
                destroyOnClose
                style={{ top: 50 }}
                styles={{
                    body: {
                        height: 'calc(100vh - 250px)',
                        overflowY: 'auto',
                        padding: '24px'
                    }
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        enabled: true,
                    }}
                >
                    {/* 应用选择 */}
                    <Form.Item
                        name="applicationId"
                        label="应用"
                        required
                        tooltip="选择要部署的应用"
                    >
                        <Select
                            placeholder="请选择应用"
                            onChange={handleAppChange}
                            disabled={isEdit}
                            showSearch
                            optionFilterProp="children"
                        >
                            {applications.map((app) => (
                                <Option key={app.id} value={app.id}>
                                    {app.appName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 工作流选择 */}
                    {!isEdit && (
                        <Form.Item
                            name="workflowDefinitionId"
                            label="工作流"
                            required
                            tooltip="选择要使用的工作流"
                        >
                            <Select
                                placeholder="请选择工作流"
                                showSearch
                                optionFilterProp="children"
                            >
                                {workflowDefinitions.map((workflow) => (
                                    <Option key={workflow.id} value={workflow.id}>
                                        {workflow.name}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    )}

                    {/* 动态构建配置 */}
                    {selectedTemplate?.buildVariablesSchema?.properties && (
                        <>
                            {/* 使用 BetaSchemaForm 渲染普通字段 */}
                            <BetaSchemaForm
                                layoutType="Embed"
                                columns={convertJsonSchemaToColumns({
                                    type: 'object',
                                    properties: Object.fromEntries(
                                        Object.entries(selectedTemplate.buildVariablesSchema.properties)
                                            .filter(([_, prop]) => !prop.editorConfig)
                                            .map(([key, prop]) => [key, {
                                                ...prop,
                                                type: prop.type || 'string'  // 确保有 type 字段
                                            }])
                                    ),
                                    required: selectedTemplate.buildVariablesSchema.required || []
                                })}
                                initialValues={buildVariables}
                                onValuesChange={(_, values) => {
                                    setBuildVariables(prev => ({
                                        ...prev,
                                        ...values
                                    }));
                                }}
                            />

                            {/* 渲染编辑器字段 */}
                            {Object.entries(selectedTemplate.buildVariablesSchema.properties)
                                .filter(([_, prop]) => prop.editorConfig)
                                .map(([key, property]) => {
                                    const isFullscreen = fullscreenEditor?.key === key;
                                    
                                    const editor = (
                                        <Editor
                                            height={isFullscreen ? "calc(100vh - 55px)" : "300px"}
                                            defaultLanguage={property.editorConfig.language || 'shell'}
                                            theme={property.editorConfig.theme || 'vs-dark'}
                                            value={buildVariables[key] || property.default || ''}
                                            onChange={(value) => handleEditorChange(key, value)}
                                            options={{
                                                minimap: { enabled: isFullscreen ? true : (property.editorConfig.minimap ?? false) },
                                                fontSize: property.editorConfig.fontSize || 14,
                                                lineNumbers: property.editorConfig.lineNumbers ? 'on' : 'off',
                                                wordWrap: property.editorConfig.wordWrap ? 'on' : 'off',
                                                tabSize: property.editorConfig.tabSize || 2,
                                                scrollBeyondLastLine: false,
                                                automaticLayout: true,
                                                folding: property.editorConfig.folding ?? true,
                                                autoClosingBrackets: 'always',
                                                autoClosingQuotes: 'always',
                                                formatOnPaste: true,
                                                formatOnType: true,
                                                suggestOnTriggerCharacters: property.editorConfig.autoComplete ?? true,
                                                renderWhitespace: 'boundary',
                                            }}
                                        />
                                    );

                                    return isFullscreen ? (
                                        <Modal
                                            key={key}
                                            title={property.title || key}
                                            open={true}
                                            onCancel={() => setFullscreenEditor(null)}
                                            footer={null}
                                            width="100vw"
                                            styles={{
                                                body: { padding: 0 },
                                                mask: { backgroundColor: 'rgba(0, 0, 0, 0.65)' },
                                                content: { 
                                                    position: 'fixed',
                                                    top: 0,
                                                    left: 0,
                                                    right: 0,
                                                    bottom: 0,
                                                    margin: 0,
                                                    padding: 0,
                                                    width: '100vw',
                                                    height: '100vh'
                                                }
                                            }}
                                        >
                                            {editor}
                                        </Modal>
                                    ) : (
                                        <Form.Item
                                            key={key}
                                            label={
                                                <Space>
                                                    {property.title || key}
                                                    <Button
                                                        type="text"
                                                        icon={<FullscreenOutlined />}
                                                        onClick={() => setFullscreenEditor({
                                                            key,
                                                            title: property.title || key
                                                        })}
                                                    />
                                                </Space>
                                            }
                                            required={selectedTemplate.buildVariablesSchema.required?.includes(key)}
                                            tooltip={property.description}
                                        >
                                            {editor}
                                        </Form.Item>
                                    );
                                })}
                        </>
                    )}

                    {/* 状态 */}
                    <Form.Item
                        name="enabled"
                        label="状态"
                        valuePropName="checked"
                        tooltip="是否启用该配置"
                    >
                        <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default DeploymentConfigModal; 