<script setup lang="ts">
import { useExternalHooks } from '@/app/composables/useExternalHooks';
import { useTelemetry } from '@/app/composables/useTelemetry';
import { useCredentialsStore } from '../credentials.store';
import { useUIStore } from '@/app/stores/ui.store';
import { createEventBus } from '@n8n/utils/event-bus';
import { computed, onMounted, ref } from 'vue';
import { CREDENTIAL_SELECT_MODAL_KEY } from '../credentials.constants';
import Modal from '@/app/components/Modal.vue';
import { useI18n } from '@n8n/i18n';

import { N8nButton, N8nIcon, N8nOption, N8nSelect } from '@n8n/design-system';
import { injectWorkflowDocumentStore } from '@/app/stores/workflowDocument.store';
import { useInstanceAiCredentialHelp } from '@/features/ai/instanceAi/composables/useInstanceAiCredentialHelp';
const externalHooks = useExternalHooks();
const telemetry = useTelemetry();
const i18n = useI18n();

const modalBus = ref(createEventBus());
const selected = ref('');
const loading = ref(true);
const selectRef = ref<HTMLSelectElement>();

const credentialsStore = useCredentialsStore();
const uiStore = useUIStore();
const workflowDocumentStore = injectWorkflowDocumentStore();
const instanceAiCredentialHelp = useInstanceAiCredentialHelp();

const searchQuery = ref('');

onMounted(async () => {
	try {
		await credentialsStore.fetchCredentialTypes(false);
	} catch (e) {}

	loading.value = false;

	setTimeout(() => {
		if (selectRef.value) {
			selectRef.value.focus();
		}
	}, 0);
});

// Exclude purpose built credentials for ChatHub
const allSelectableCredentialTypes = computed(() =>
	credentialsStore.allCredentialTypes.filter((c) => !c.name.startsWith('chatHub')),
);

const selectableCredentialTypes = computed(() => {
	if (!searchQuery.value) return allSelectableCredentialTypes.value;
	const q = searchQuery.value.toLowerCase();
	return allSelectableCredentialTypes.value.filter((c) => c.displayName.toLowerCase().includes(q));
});

function filterCredentials(query: string) {
	searchQuery.value = query;
}

function onSelect(type: string) {
	selected.value = type;
}

function openCredentialType() {
	modalBus.value.emit('close');
	// Carry the credentials-list credential help into the new-credential dialog so
	// it offers the Instance AI button (not the legacy assistant) like the rest of
	// the list does.
	uiStore.openNewCredential(
		selected.value,
		false,
		false,
		undefined,
		undefined,
		undefined,
		undefined,
		{
			instanceAiCredentialHelp: instanceAiCredentialHelp(),
		},
	);

	const telemetryPayload = {
		credential_type: selected.value,
		source: 'primary_menu',
		new_credential: true,
		workflow_id: workflowDocumentStore.value.workflowId,
	};

	telemetry.track('User opened Credential modal', telemetryPayload);
	void externalHooks.run('credentialsSelectModal.openCredentialType', telemetryPayload);
}
</script>

<template>
	<Modal
		:name="CREDENTIAL_SELECT_MODAL_KEY"
		:event-bus="modalBus"
		width="50%"
		:center="true"
		:loading="loading"
		max-width="460px"
		min-height="250px"
	>
		<template #header>
			<h2 :class="$style.title">
				{{ i18n.baseText('credentialSelectModal.addNewCredential') }}
			</h2>
		</template>
		<template #content>
			<div>
				<div :class="$style.subtitle">
					{{ i18n.baseText('credentialSelectModal.selectAnAppOrServiceToConnectTo') }}
				</div>
				<N8nSelect
					ref="selectRef"
					filterable
					default-first-option
					:placeholder="i18n.baseText('credentialSelectModal.searchForApp')"
					size="xlarge"
					:model-value="selected"
					:filter-method="filterCredentials"
					data-test-id="new-credential-type-select"
					@update:model-value="onSelect"
				>
					<template #prefix>
						<N8nIcon icon="search" />
					</template>
					<N8nOption
						v-for="credential in selectableCredentialTypes"
						:key="credential.name"
						:value="credential.name"
						:label="credential.displayName"
						filterable
						data-test-id="new-credential-type-select-option"
					/>
				</N8nSelect>
			</div>
		</template>
		<template #footer>
			<div :class="$style.footer">
				<N8nButton
					:label="i18n.baseText('credentialSelectModal.continue')"
					float="right"
					size="large"
					:disabled="!selected"
					data-test-id="new-credential-type-button"
					@click="openCredentialType"
				/>
			</div>
		</template>
	</Modal>
</template>

<style module lang="scss">
.title {
	font-size: var(--font-size--xl);
	line-height: var(--line-height--md);
}

.subtitle {
	margin-bottom: var(--spacing--sm);
	font-size: var(--font-size--md);
	line-height: var(--line-height--xl);
}
</style>
