<template>
	<n-modal
		v-model:show="showDialog"
		preset="card"
		:title="$t('Add New Webhook')"
		:style="modalStyle"
		:mask-closable="true"
		:close-on-esc="true"
		class="add-webhook-modal"
	>
		<template #header>
			<span class="text-lg font-semibold">{{ $t('Add New Webhook') }}</span>
		</template>
		<n-space vertical :size="20">
			<n-form-item :label="$t('Endpoint')" :required="true">
				<n-input
					v-model:value="endpoint"
					placeholder=""
					:size="inputSize"
					class="w-full"
				/>
			</n-form-item>
			<n-form-item :label="$t('Secret Key')">
				<n-input
					v-model:value="secret"
					placeholder=""
					:size="inputSize"
					class="w-full"
				>
					<template #suffix>
						<n-icon
							class="cursor-pointer text-gray-500 hover:text-gray-700"
							@click="generateRandomSecret"
						>
							<RefreshIcon />
						</n-icon>
					</template>
				</n-input>
			</n-form-item>
			<n-alert type="info" class="mb-2">
				<template #header>
					<strong>{{ $t('Note') }}:</strong>
				</template>
				{{ $t('The secret key is optional. View') }}
				<a href="https://jingrow.com/docs/webhook-introduction" class="text-primary underline" target="_blank">
					{{ $t('documentation') }}
				</a>
				{{ $t('to learn more') }}
			</n-alert>
			<div class="mt-4">
				<p class="text-base font-medium text-gray-900 mb-4">
					{{ $t('Select Webhook Events') }}
				</p>
				<n-spin :show="$resources.events.loading">
					<n-space vertical :size="12" v-if="!$resources.events.loading">
						<div
							v-for="event in localizedEvents"
							:key="event.name"
							class="flex items-center justify-between p-3 rounded border border-gray-200 hover:bg-gray-50"
						>
							<div class="flex-1">
								<div class="text-sm font-medium text-gray-900">
									{{ event.title || event.name }}
								</div>
								<div v-if="event.description" class="text-xs text-gray-500 mt-1">
									{{ event.description }}
								</div>
							</div>
							<n-switch
								:value="isEventSelected(event.name)"
								@update:value="selectEvent(event.name)"
								size="medium"
							/>
						</div>
					</n-space>
				</n-spin>
			</div>
			<n-alert
				v-if="errorMessage || $resources.addWebhook.error"
				type="error"
				:title="errorMessage || $resources.addWebhook.error"
			/>
		</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
					type="primary"
					:loading="$resources.addWebhook.loading"
					@click="addWebhook"
					:block="isMobile"
					:size="buttonSize"
				>
					{{ $t('Add Webhook') }}
				</n-button>
			</n-space>
		</template>
	</n-modal>
</template>

<script>
import {
	NModal,
	NFormItem,
	NInput,
	NSpace,
	NAlert,
	NButton,
	NSwitch,
	NIcon,
	NSpin,
} from 'naive-ui';
import { toast } from 'vue-sonner';
import RefreshIcon from '~icons/lucide/refresh-ccw';

export default {
	components: {
		NModal,
		NFormItem,
		NInput,
		NSpace,
		NAlert,
		NButton,
		NSwitch,
		NIcon,
		NSpin,
		RefreshIcon,
	},
	emits: ['success', 'update:modelValue'],
	props: {
		modelValue: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			endpoint: '',
			secret: '',
			selectedEvents: [],
			errorMessage: '',
			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';
		},
		localizedEvents() {
			if (!this.$resources.events.data) return [];
			
			return this.$resources.events.data.map(event => {
				const localizedEvent = { ...event };
				
				if (localizedEvent.name === 'Site Status Update') {
					localizedEvent.title = this.$t('Site Status Update');
					localizedEvent.description = this.$t('Pending, Installing, Updating, Active, Inactive, Abnormal, Archived, Paused');
				} else if (localizedEvent.name === 'Site Plan Change') {
					localizedEvent.title = this.$t('Site Plan Change');
					localizedEvent.description = this.$t('Get notifications for site subscription plan changes');
				} else {
					if (!localizedEvent.title) {
						localizedEvent.title = localizedEvent.name;
					}
					if (!localizedEvent.description) {
						localizedEvent.description = '';
					}
				}
				
				return localizedEvent;
			});
		}
	},
	mounted() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
		if (this.selectedEvents.length) {
			this.selectedEvents = this.selectedEvents.map(event => event.name);
		}
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.handleResize);
	},
	methods: {
		handleResize() {
			this.windowWidth = window.innerWidth;
		},
		generateRandomSecret() {
			this.secret = Array(30)
				.fill(0)
				.map(
					() =>
						'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'[
							Math.floor(Math.random() * 62)
						]
				)
				.join('');
		},
		selectEvent(event) {
			if (this.selectedEvents.includes(event)) {
				this.selectedEvents = this.selectedEvents.filter(e => e !== event);
			} else {
				this.selectedEvents.push(event);
			}
		},
		isEventSelected(event) {
			return this.selectedEvents.includes(event);
		},
		addWebhook() {
			if (!this.endpoint) {
				this.errorMessage = this.$t('Please provide a valid webhook endpoint');
				return;
			}
			if (!this.selectedEvents.length) {
				this.errorMessage = this.$t('Please enable at least one event');
				return;
			}
			this.errorMessage = '';
			this.$resources.addWebhook.submit();
		},
		hide() {
			this.showDialog = false;
			this.endpoint = '';
			this.secret = '';
			this.selectedEvents = [];
			this.errorMessage = '';
		}
	},
	resources: {
		events() {
			return {
				url: 'jcloud.api.webhook.available_events',
				inititalData: [],
				auto: true
			};
		},
		addWebhook() {
			return {
				url: 'jcloud.api.webhook.add',
				params: {
					endpoint: this.endpoint,
					secret: this.secret,
					events: this.selectedEvents
				},
				onSuccess() {
					toast.success(this.$t('Webhook added successfully'));
					this.hide();
					this.$emit('success');
				}
			};
		}
	}
};
</script>

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

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

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

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

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

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

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

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

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

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