import React, { useEffect } from 'react';
import {Tabs, TabsProps} from 'antd';
import {Cell} from '@antv/x6';
import {NodeDefinitionResponse} from "@/pages/Workflow/NodeDesign/types";
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTitle,
    SheetFooter,
} from "@/components/ui/sheet";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import { convertJsonSchemaToColumns } from '@/utils/jsonSchemaUtils';
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

interface NodeConfigDrawerProps {
    visible: boolean;
    node: Cell | null;
    nodeDefinition: NodeDefinitionResponse | null;
    onOk: (values: any) => void;
    onCancel: () => void;
}

interface Variables {
    [key: string]: any;
}

const NodeConfigDrawer: React.FC<NodeConfigDrawerProps> = ({
    visible,
    node,
    nodeDefinition,
    onOk,
    onCancel,
}) => {
    const [panelValues, setPanelValues] = React.useState<Variables>({});
    const [localValues, setLocalValues] = React.useState<Variables>({});
    useEffect(() => {
        if (nodeDefinition) {
            // 使用修改后的 schema 获取字段配置
            const panelColumns = convertJsonSchemaToColumns(nodeDefinition.panelVariablesSchema || { type: 'object', properties: {} });
            const localColumns = convertJsonSchemaToColumns(nodeDefinition.localVariablesSchema || { type: 'object', properties: {} });
            // 初始化表单值，包括默认值
            const initialPanelValues = panelColumns.reduce((acc, column) => {
                if (column.initialValue !== undefined) {
                    acc[column.dataIndex] = column.initialValue;
                }
                return acc;
            }, {} as Variables);

            const initialLocalValues = localColumns.reduce((acc, column) => {
                if (column.initialValue !== undefined) {
                    acc[column.dataIndex] = column.initialValue;
                }
                return acc;
            }, {} as Variables);

            // 设置初始值
            setPanelValues({
                ...initialPanelValues,
                ...(nodeDefinition.panelVariables || {}),
                // 如果是新节点，使用节点的 nodeType 和 nodeName 作为默认值
                ...(node && {
                    code: nodeDefinition.nodeType,
                    name: nodeDefinition.nodeName
                })
            });
            setLocalValues({
                ...initialLocalValues,
                ...(nodeDefinition.localVariables || {})
            });
        }
    }, [nodeDefinition]);

    const handleSubmit = () => {
        const updatedNodeDefinition = {
            ...nodeDefinition,
            panelVariables: panelValues,
            localVariables: localValues
        };
        onOk(updatedNodeDefinition);
    };

    const renderFormField = (column: any, value: any, onChange: (value: any) => void) => {
        console.log('renderFormField 被调用:', { column, value });
        
        // 特殊处理 code 字段
        const isCodeField = column.dataIndex === 'code';
        const isReadOnly = isCodeField || column.readonly === true;
        
        const props = {
            value: value || '',
            onChange: (e: any) => !isReadOnly && onChange(e.target?.value ?? e),
            placeholder: column.fieldProps?.placeholder,
            disabled: isReadOnly,
            readOnly: isReadOnly,
            className: `${isReadOnly ? "bg-gray-100" : ""} ${column.fieldProps?.className || ""}`,
        };

        switch (column.valueType) {
            case 'select':
                return (
                    <Select
                        value={value}
                        onValueChange={onChange}
                        disabled={column.readonly === true}
                    >
                        <SelectTrigger>
                            <SelectValue placeholder={column.fieldProps?.placeholder} />
                        </SelectTrigger>
                        <SelectContent>
                            {column.fieldProps?.options?.map((option: any) => (
                                <SelectItem key={option.value} value={option.value}>
                                    {option.label}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                );
            case 'switch':
                return (
                    <Switch
                        checked={value}
                        onCheckedChange={onChange}
                        disabled={column.readonly === true}
                    />
                );
            case 'textarea':
            case 'code':
                return <Textarea {...props} />;
            case 'digit':
                return <Input {...props} type="number" />;
            default:
                return <Input {...props} />;
        }
    };

    const renderFormFields = (schema: any, values: Variables, onChange: (key: string, value: any) => void) => {
        if (!schema?.properties) return null;

        const columns = convertJsonSchemaToColumns(schema);
        
        return columns.map(column => (
            <div key={column.dataIndex} className="space-y-2">
                <Label>{column.title}</Label>
                {renderFormField(
                    column,
                    values[column.dataIndex],
                    (value) => onChange(column.dataIndex, value)
                )}
            </div>
        ));
    };

    const handlePanelChange = (key: string, value: any) => {
        setPanelValues(prev => ({...prev, [key]: value}));
    };

    const handleLocalChange = (key: string, value: any) => {
        setLocalValues(prev => ({...prev, [key]: value}));
    };

    const handleFormChange = (key: string, value: any) => {
        setFormValues(prev => ({...prev, [key]: value}));
    };

    const items: TabsProps['items'] = [
        nodeDefinition?.panelVariablesSchema && {
            key: 'panel',
            label: '面板变量',
            children: (
                <div className="space-y-4">
                    {renderFormFields(nodeDefinition.panelVariablesSchema, panelValues, handlePanelChange)}
                </div>
            )
        },
        nodeDefinition?.localVariablesSchema && {
            key: 'local',
            label: '环境变量',
            children: (
                <div className="space-y-4">
                    {renderFormFields(nodeDefinition.localVariablesSchema, localValues, handleLocalChange)}
                </div>
            )
        }
    ].filter(Boolean) as TabsProps['items'];

    return (
        <Sheet open={visible} onOpenChange={(open) => !open && onCancel()}>
            <SheetContent side="right" className="w-[480px] sm:w-[480px]">
                <div className="flex flex-col h-full">
                    <SheetHeader>
                        <SheetTitle>编辑节点 - {nodeDefinition?.nodeName || ''}</SheetTitle>
                    </SheetHeader>
                    <div className="flex-1 overflow-y-auto py-6">
                        <Tabs items={items} className="border-none"/>
                    </div>
                    <div className="shrink-0 border-t bg-background p-4">
                        <div className="flex justify-end gap-2">
                            <Button variant="outline" onClick={onCancel}>
                                取消
                            </Button>
                            <Button onClick={handleSubmit}>
                                确定
                            </Button>
                        </div>
                    </div>
                </div>
            </SheetContent>
        </Sheet>
    );
};

export default NodeConfigDrawer;
