import {
	NodeConnectionTypes,
	type INodeDataBaseSchema,
	type INodeType,
	type NodeVariable,
	type NodeVariableType
} from '../../Interface'
import Setter from './setter.vue'
import i18n from '@/i18n'
import { getNodeDescription, getNodeDisplayName } from '@/nodes/i18n'

export type ViewDataResultType = 'object' | 'array' | 'tree'

export interface ViewDataTreeFields {
	id: string
	parentId: string
	children: string
	text: string
}

export interface ViewDataTreeConfig {
	fields: ViewDataTreeFields
}

export type ViewDataData = INodeDataBaseSchema & {
	code: string
	result_type: ViewDataResultType
	tree_config: ViewDataTreeConfig
	index_variable: NodeVariable
	page_size: number
}

export const getViewDataTableOutputType = (
	resultType: ViewDataResultType
): Extract<NodeVariableType, 'object' | 'array[object]'> => {
	return resultType === 'object' ? 'object' : 'array[object]'
}

export const createDefaultViewDataTreeConfig = (): ViewDataTreeConfig => ({
	fields: {
		id: 'id',
		parentId: 'parentId',
		children: 'children',
		text: 'name'
	}
})

export const viewDataNode: INodeType = {
	version: ['1'],
	displayName: getNodeDisplayName('view-data'),
	name: 'view-data',
	Setter,
	description: getNodeDescription('view-data'),
	group: 'data',
	icon: 'lucide:table-properties',
	iconColor: '#0ba5ec',
	inputs: [NodeConnectionTypes.main],
	outputs: [NodeConnectionTypes.main],
	validate: (data: ViewDataData) => {
		if (!data?.code?.trim()) {
			return i18n.t('pages.viewDataSetter.codeRequired')
		}

		if (data?.result_type === 'tree') {
			const fields = data?.tree_config?.fields
			if (!fields?.id?.trim()) return i18n.t('pages.viewDataSetter.treeFieldRequired')
			if (!fields?.parentId?.trim()) return i18n.t('pages.viewDataSetter.treeFieldRequired')
			if (!fields?.children?.trim()) return i18n.t('pages.viewDataSetter.treeFieldRequired')
		}

		return false
	},
	getSubtitle: (data: ViewDataData) => {
		return data?.code || ''
	},
	schema: {
		appAgentId: '',
		parentId: '',
		position: {
			x: 20,
			y: 30
		},
		width: 96,
		height: 96,
		selected: false,
		nodeType: 'view-data',
		zIndex: 1,
		data: {}
	}
}
