<template>
	<n-modal
		v-model:show="showDialog"
		preset="card"
		:title="$t('Activate Webhook')"
		:style="modalStyle"
		:mask-closable="true"
		:close-on-esc="true"
		class="activate-webhook-modal"
	>
		<template #header>
			<span class="text-lg font-semibold">{{ $t('Activate Webhook') }}</span>
		</template>
		<n-space vertical :size="20">
			<n-form-item :label="$t('Endpoint')">
				<n-input
					:value="webhook.endpoint"
					disabled
					:size="inputSize"
					class="w-full"
				/>
			</n-form-item>
			<div v-if="request">
				<p class="text-xs text-gray-600 mb-2">{{ $t('Request') }}</p>
				<pre class="mt-2 whitespace-pre-wrap rounded bg-gray-50 px-3 py-2 text-sm text-gray-700 border border-gray-200">
{{ request }}
				</pre>
			</div>
			<n-form-item v-if="response_status_code" :label="$t('Response Status Code')">
				<n-input
					:value="response_status_code"
					disabled
					:size="inputSize"
					class="w-full"
				/>
			</n-form-item>
			<div v-if="response">
				<p class="text-xs text-gray-600 mb-2">{{ $t('Response') }}</p>
				<pre class="mt-2 max-h-52 overflow-y-auto whitespace-pre-wrap rounded bg-gray-50 px-3 py-2 text-sm text-gray-700 border border-gray-200">
{{ response }}
				</pre>
			</div>
			<div class="flex items-center" v-if="validated">
				<n-icon class="h-5 w-5 text-green-600 mr-2">
					<CheckIcon />
				</n-icon>
				<div class="text-sm font-medium text-gray-700">
					{{ $t('Endpoint validated') }}
				</div>
			</div>
			<n-alert v-if="errorMessage" type="error" :title="errorMessage" />
		</n-space>
		<template #action>
			<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
				<n-button @click="hide" :block="isMobile" :size="buttonSize">
					{{ $t('Cancel') }}
				</n-button>
				<n-button
					v-if="!validated"
					type="primary"
					:loading="$resources.validateEndpoint.loading"
					@click="$resources.validateEndpoint.submit()"
					:block="isMobile"
					:size="buttonSize"
				>
					{{ $t('Validate Webhook') }}
				</n-button>
				<n-button
					v-if="validated"
					type="primary"
					:loading="$resources.activateWebhook.loading"
					@click="$resources.activateWebhook.submit()"
					:block="isMobile"
					:size="buttonSize"
				>
					{{ $t('Activate Webhook') }}
				</n-button>
			</n-space>
		</template>
	</n-modal>
</template>

<script>
import {
	NModal,
	NFormItem,
	NInput,
	NSpace,
	NAlert,
	NButton,
	NIcon,
} from 'naive-ui';
import { toast } from 'vue-sonner';
import CheckIcon from '~icons/lucide/check';

export default {
	components: {
		NModal,
		NFormItem,
		NInput,
		NSpace,
		NAlert,
		NButton,
		NIcon,
		CheckIcon,
	},
	emits: ['success', 'update:modelValue'],
	props: {
		webhook: {
			type: Object,
			required: true
		},
		modelValue: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			errorMessage: '',
			validated: false,
			request: null,
			response: null,
			response_status_code: null,
			windowWidth: window.innerWidth,
		};
	},
	computed: {
		showDialog: {
			get() {
				return this.modelValue;
			},
			set(value) {
				this.$emit('update:modelValue', value);
			}
		},
		isMobile() {
			return this.windowWidth <= 768;
		},
		modalStyle() {
			return {
				width: this.isMobile ? '95vw' : '800px',
				maxWidth: this.isMobile ? '95vw' : '90vw',
			};
		},
		inputSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		buttonSize() {
			return this.isMobile ? 'medium' : 'medium';
		},
	},
	mounted() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.handleResize);
	},
	methods: {
		handleResize() {
			this.windowWidth = window.innerWidth;
		},
		hide() {
			this.showDialog = false;
			this.errorMessage = '';
			this.validated = false;
			this.request = null;
			this.response = null;
			this.response_status_code = null;
		}
	},
	resources: {
		validateEndpoint() {
			return {
				url: 'jcloud.api.client.run_pg_method',
				makeParams() {
					return {
						dt: 'Jcloud Webhook',
						dn: this.webhook.name,
						method: 'validate_endpoint'
					};
				},
				onSuccess: result => {
					const data = result.message;
					this.request = data.request;
					this.response = data.response;
					this.response_status_code = data.response_status_code;
					if (data.success) {
						this.errorMessage = '';
						this.validated = true;
					} else {
						this.validated = false;
						this.errorMessage = this.$t('Endpoint should return a status code between 200 and 300. Please check the endpoint and try again.');
					}
				},
				onError: e => {
					console.error(e);
					this.errorMessage = e.message;
				}
			};
		},
		activateWebhook() {
			return {
				url: 'jcloud.api.client.run_pg_method',
				makeParams() {
					return {
						dt: 'Jcloud Webhook',
						dn: this.webhook.name,
						method: 'activate'
					};
				},
				onSuccess(e) {
					toast.success(this.$t('Webhook activated successfully'));
					this.hide();
					this.$emit('success');
				},
				onError(e) {
					console.error(e);
					this.errorMessage = e.message;
				}
			};
		}
	}
};
</script>

<style scoped>
:deep(.activate-webhook-modal .n-card) {
	width: 800px;
	max-width: 90vw;
}

:deep(.activate-webhook-modal .n-card-body) {
	padding: 24px;
}

:deep(.activate-webhook-modal .n-form-item) {
	margin-bottom: 0;
}

:deep(.activate-webhook-modal .n-input) {
	width: 100%;
}

:deep(.activate-webhook-modal .n-card__action) {
	padding: 16px 24px;
}

@media (max-width: 768px) {
	:deep(.activate-webhook-modal .n-card) {
		width: 95vw !important;
		max-width: 95vw !important;
		margin: 20px auto;
		border-radius: 12px;
	}

	:deep(.activate-webhook-modal .n-card-body) {
		padding: 20px 16px;
	}

	:deep(.activate-webhook-modal .n-card__header) {
		padding: 16px;
		font-size: 18px;
	}

	:deep(.activate-webhook-modal .n-card__action) {
		padding: 12px 16px;
	}

	:deep(.activate-webhook-modal .n-button) {
		width: 100%;
		font-size: 16px;
		height: 44px;
	}
}
</style>
