<template>
	<div
		v-if="$jsiteServer?.pg"
		class="grid grid-cols-1 items-start gap-5 lg:grid-cols-2"
	>
		<!-- 左侧区块：基本信息 -->
		<div class="col-span-1 space-y-5">
			<!-- 当前套餐卡片 -->
			<div class="rounded-md border">
				<div class="h-12 border-b px-5 py-4">
					<h2 class="text-lg font-medium text-gray-900">{{ $t('Current Plan') }}</h2>
				</div>
				<div class="p-5">
					<div class="flex h-full flex-col sm:flex-row sm:items-center sm:justify-between">
						<div class="mb-4 sm:mb-0">
							<div v-if="$jsiteServer.pg.plan_price" class="text-lg font-bold text-green-600">
								¥{{ $jsiteServer.pg.plan_price }}/月
							</div>
							
							<div v-if="$jsiteServer.pg.end_date" class="mt-2 inline-flex items-center rounded-full bg-amber-50 px-4 py-2 text-sm font-medium text-amber-800">
								<ClockIcon class="mr-1.5 h-4 w-4 text-amber-500" />
								{{ $t('Expiry Date') }}: {{ $format.date($jsiteServer.pg.end_date) }}
							</div>
						</div>
						<div class="flex gap-2">
							<Button 
								@click="renewServer"
								:loading="$jsiteServer.renew?.loading"
								class="px-5 !bg-[#1fc76f] !hover:bg-[#1bb85f] !text-white"
							>
								{{ $t('Renew') }}
							</Button>
							<Button 
								@click="upgradeServer"
								:loading="upgradeLoading"
								class="px-5 !bg-[#3b82f6] !hover:bg-[#2563eb] !text-white"
							>
								{{ $t('Upgrade') }}
							</Button>
						</div>
					</div>
				</div>
			</div>

			<!-- 服务器配置 -->
			<div class="rounded-md border">
				<div class="h-12 border-b px-5 py-4">
					<h2 class="text-lg font-medium text-gray-900">{{ $t('Server Configuration') }}</h2>
				</div>
				<div class="p-5">
					<div class="space-y-3">
						<div class="flex justify-between items-center">
							<span class="text-gray-600">{{ $t('CPU') }}:</span>
							<span class="text-lg font-semibold text-blue-600">{{ $jsiteServer.pg.cpu || $t('Unknown') }} {{ $t('cores') }}</span>
						</div>
						<div class="flex justify-between items-center">
							<span class="text-gray-600">{{ $t('Memory') }}:</span>
							<span class="text-lg font-semibold text-green-600">{{ $jsiteServer.pg.memory || $t('Unknown') }}GB</span>
						</div>
						<div class="flex justify-between items-center">
							<span class="text-gray-600">{{ $t('System Disk') }}:</span>
							<span class="text-lg font-semibold text-purple-600">{{ $jsiteServer.pg.disk_size || $t('Unknown') }}GB</span>
						</div>
						<div class="flex justify-between items-center">
							<span class="text-gray-600">{{ $t('Bandwidth') }}:</span>
							<span class="text-lg font-semibold text-orange-600">{{ $jsiteServer.pg.bandwidth || $t('Unknown') }}Mbps</span>
						</div>
					</div>
				</div>
			</div>
			
			<!-- 服务器信息 -->
			<div class="rounded-md border">
				<div class="h-12 border-b px-5 py-4">
					<h2 class="text-lg font-medium text-gray-900">{{ $t('Server Information') }}</h2>
				</div>
				<div>
					<div
						v-for="info in serverInformation"
						:key="info.label"
						class="flex items-center px-5 py-3 last:pb-5 even:bg-gray-50/70"
					>
						<div class="w-1/3 text-base text-gray-600">{{ info.label }}</div>
						<div
							class="flex w-2/3 items-center space-x-2 text-base text-gray-900"
						>
							<div v-if="info.prefix">
								<component :is="info.prefix" />
							</div>
							<!-- 状态字段使用Badge组件 -->
							<div v-if="info.label === '状态'">
								<Badge :label="info.value" />
							</div>
							<!-- 服务器名称特殊处理 - 支持内联编辑 -->
							<div v-else-if="info.label === $t('Server Name')" class="flex-1 min-w-0">
								<div v-if="!editingServerName" 
									@click="startEditServerName"
									class="group flex items-center cursor-pointer rounded-md px-2 py-1 -mx-2 -my-1 hover:bg-gray-100 transition-colors duration-200"
									:title="$t('Click to edit server name')"
								>
									<span class="truncate">{{ info.value }}</span>
									<svg class="ml-2 h-4 w-4 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path>
									</svg>
								</div>
								<div v-else class="flex items-center space-x-2">
									<input 
										ref="serverNameInput"
										v-model="editServerNameValue"
										@keyup.enter="saveServerName"
										@keyup.escape="cancelEditServerName"
										@blur="handleInputBlur"
										class="flex-1 px-2 py-1 text-sm border border-blue-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent shadow-sm"
										:disabled="saveServerNameLoading"
										maxlength="100"
										:placeholder="$t('Please enter server name')"
									/>
									<button 
										@click="saveServerName"
										:disabled="saveServerNameLoading"
										class="p-1 text-green-600 hover:text-green-700 disabled:opacity-50 transition-colors duration-200"
										:title="$t('Save')"
									>
										<svg v-if="!saveServerNameLoading" class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
										</svg>
										<svg v-else class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
											<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
											<path class="opacity-75" fill="currentColor" d="m12 6a6 6 0 0 1 6 6h4a10 10 0 0 0-10-10v4z"></path>
										</svg>
									</button>
									<button 
										@click="cancelEditServerName"
										:disabled="saveServerNameLoading"
										class="p-1 text-gray-500 hover:text-gray-700 disabled:opacity-50 transition-colors duration-200"
										:title="$t('Cancel')"
									>
										<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
										</svg>
									</button>
								</div>
							</div>
							<!-- 其他信息正常显示 -->
							<span v-else>
								{{ info.value }}
							</span>
							<div v-if="info.suffix">
								<component :is="info.suffix" />
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<!-- 右侧区块：配置信息和操作 -->
		<div class="col-span-1 space-y-5">
			<!-- 操作 -->
			<div class="rounded-md border">
				<div class="h-12 border-b px-5 py-4">
					<h2 class="text-lg font-medium text-gray-900">{{ $t('Actions') }}</h2>
				</div>
				<div class="p-5">
					<div class="flex flex-wrap gap-2">
						<Button 
							@click="restartServer"
							:loading="restartLoading"
							variant="outline"
							class="bg-gray-100 text-gray-700 hover:bg-gray-200"
						>
							{{ $t('Restart') }}
						</Button>
						<Button 
							@click="forceRestartServer"
							:loading="forceRestartLoading"
							variant="outline"
							class="bg-orange-50 text-orange-700 hover:bg-orange-100 border-orange-200"
						>
							{{ $t('Force Restart') }}
						</Button>
						<Button 
							@click="resetPassword"
							:loading="resetPasswordLoading"
							variant="outline"
							class="bg-gray-100 text-gray-700 hover:bg-gray-200"
						>
							{{ $t('Reset Password') }}
						</Button>
						<Button 
							@click="resetKeyPair"
							:loading="resetKeyPairLoading"
							variant="outline"
							class="bg-gray-100 text-gray-700 hover:bg-gray-200"
						>
							{{ $t('Reset Key Pair') }}
						</Button>
						<Button 
							@click="deleteKeyPair"
							:loading="deleteKeyPairLoading"
							variant="outline"
							class="bg-red-50 text-red-700 hover:bg-red-100 border-red-200"
						>
							{{ $t('Delete Key Pair') }}
						</Button>
						<Button 
							@click="resetSystem"
							:loading="resetSystemLoading"
							variant="outline"
							class="bg-red-50 text-red-700 hover:bg-red-100 border-red-200"
						>
							{{ $t('Reset System') }}
						</Button>
					</div>
				</div>
			</div>
						
			<!-- SSH连接信息 -->
			<div class="rounded-md border">
				<div class="h-12 border-b px-5 py-4">
					<h2 class="text-lg font-medium text-gray-900">{{ $t('SSH Connection') }}</h2>
				</div>
				<div class="p-5">
					<div class="space-y-3">
						<div class="flex justify-between">
							<span class="text-gray-600">{{ $t('SSH Port') }}:</span>
							<span class="font-mono text-gray-900">{{ $jsiteServer.pg.ssh_port || '22' }}</span>
						</div>
						<div class="flex justify-between">
							<span class="text-gray-600">{{ $t('SSH User') }}:</span>
							<span class="font-mono text-gray-900">{{ $jsiteServer.pg.ssh_user || 'root' }}</span>
						</div>
						<div class="flex justify-between items-center">
							<span class="text-gray-600">{{ $t('Server Password') }}:</span>
							<div class="flex items-center space-x-2">
								<span class="font-mono text-gray-900">
									{{ showPassword ? decryptedPassword : ($jsiteServer.pg.password || $t('Not Set')) }}
								</span>
								<button
									v-if="$jsiteServer.pg.password"
									@click="togglePassword"
									class="text-gray-500 hover:text-gray-700 transition-colors"
									:title="showPassword ? $t('Hide Password') : $t('Show Password')"
								>
									<EyeIcon v-if="!showPassword" class="h-4 w-4" />
									<EyeOffIcon v-else class="h-4 w-4" />
								</button>
							</div>
						</div>
						<div class="flex justify-between">
							<span class="text-gray-600">{{ $t('Key Pair Name') }}:</span>
							<span class="font-mono text-gray-900">{{ $jsiteServer.pg.key_pair_name || $t('Not Set') }}</span>
						</div>
						<div class="flex flex-col">
							<span class="text-gray-600 mb-2">{{ $t('Private Key') }}:</span>
							<div v-if="$jsiteServer.pg.private_key" class="bg-gray-50 p-3 rounded border relative">
								<button
									@click="copyPrivateKey"
									class="absolute top-2 right-2 p-1 text-gray-500 hover:text-gray-700 transition-colors rounded"
									:title="copySuccess ? $t('Copied!') : $t('Copy Private Key')"
								>
									<CopyIcon class="h-4 w-4" />
								</button>
								<pre class="font-mono text-xs text-gray-900 whitespace-pre-wrap break-all pr-8">{{ $jsiteServer.pg.private_key }}</pre>
							</div>
							<span v-else class="font-mono text-gray-900">{{ $t('Not Set') }}</span>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { getCachedDocumentResource, Badge, Tooltip, Button, createResource } from 'jingrow-ui';
import { h, defineAsyncComponent } from 'vue';
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../utils/toast';
import { renderDialog, confirmDialog } from '../utils/components';
import EyeIcon from '~icons/lucide/eye';
import EyeOffIcon from '~icons/lucide/eye-off';
import ClockIcon from '~icons/lucide/clock';
import InfoIcon from '~icons/lucide/info';
import CopyIcon from '~icons/lucide/copy';

export default {
	name: 'JsiteServerOverview',
	props: ['server'],
	components: {
		Badge,
		Button,
		EyeIcon,
		EyeOffIcon,
		ClockIcon,
		InfoIcon,
		CopyIcon,
	},
	data() {
		return {
			showPassword: false,
			decryptedPassword: null,
			restartLoading: false,
			forceRestartLoading: false,
			resetPasswordLoading: false,
			resetKeyPairLoading: false,
			deleteKeyPairLoading: false,
			resetSystemLoading: false,
			upgradeLoading: false,
			copySuccess: false,
			editingServerName: false,
			editServerNameValue: '',
			saveServerNameLoading: false,
		};
	},
	methods: {
		getStatusText(status) {
			const statusMap = {
				'Pending': this.$t('Pending'),
				'Starting': this.$t('Starting'),
				'Running': this.$t('Running'),
				'Stopping': this.$t('Stopping'),
				'Stopped': this.$t('Stopped'),
				'Resetting': this.$t('Resetting'),
				'Upgrading': this.$t('Upgrading'),
				'Disabled': this.$t('Disabled')
			};
			return statusMap[status] || status;
		},
		getStatusVariant(status) {
			const variantMap = {
				'Pending': 'warning',
				'Starting': 'warning',
				'Running': 'success',
				'Stopping': 'warning',
				'Stopped': 'danger',
				'Resetting': 'warning',
				'Upgrading': 'warning',
				'Disabled': 'danger'
			};
			return variantMap[status] || 'default';
		},
		getRegionText(region) {
			const regionMap = {
				'cn-qingdao': this.$t('North China 1 (Qingdao)'),
				'cn-beijing': this.$t('North China 2 (Beijing)'),
				'cn-zhangjiakou': this.$t('North China 3 (Zhangjiakou)'),
				'cn-huhehaote': this.$t('North China 5 (Hohhot)'),
				'cn-hangzhou': this.$t('East China 1 (Hangzhou)'),
				'cn-shanghai': this.$t('East China 2 (Shanghai)'),
				'cn-shenzhen': this.$t('South China 1 (Shenzhen)'),
				'cn-heyuan': this.$t('South China 2 (Heyuan)'),
				'cn-chengdu': this.$t('Southwest China 1 (Chengdu)'),
				'cn-guangzhou': this.$t('South China 3 (Guangzhou)'),
				'cn-wulanchabu': this.$t('North China 6 (Ulanqab)'),
				'cn-nanjing': this.$t('East China 5 (Nanjing)'),
				'cn-fuzhou': this.$t('East China 6 (Fuzhou)'),
				'cn-wuhan-lr': this.$t('Central China 1 (Wuhan)'),
				'cn-hongkong': this.$t('Hong Kong'),
				'ap-southeast-1': this.$t('Singapore'),
				'ap-southeast-3': this.$t('Malaysia (Kuala Lumpur)'),
				'ap-southeast-5': this.$t('Indonesia (Jakarta)'),
				'ap-northeast-1': this.$t('Japan (Tokyo)'),
				'us-west-1': this.$t('US (Silicon Valley)'),
				'us-east-1': this.$t('US (Virginia)'),
				'eu-central-1': this.$t('Germany (Frankfurt)'),
				'eu-west-1': this.$t('UK (London)'),
				'ap-southeast-6': this.$t('Philippines (Manila)'),
				'ap-southeast-7': this.$t('Thailand (Bangkok)'),
				'ap-northeast-2': this.$t('South Korea (Seoul)')
			};
			return regionMap[region] || region;
		},
		renewServer() {
			const JsiteServerRenewalDialog = defineAsyncComponent(() => import('./JsiteServerRenewalDialog.vue'));
			
			renderDialog(h(JsiteServerRenewalDialog, {
				server: this.server,
				serverDoc: this.$jsiteServer.pg,
				onSuccess: this.onRenewalSuccess
			}));
		},
		upgradeServer() {
			const JsiteServerUpgradeDialog = defineAsyncComponent(() => import('./JsiteServerUpgradeDialog.vue'));
			
			renderDialog(h(JsiteServerUpgradeDialog, {
				server: this.server,
				serverDoc: this.$jsiteServer.pg,
				onSuccess: this.onUpgradeSuccess
			}));
		},
		async restartServer() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			confirmDialog({
				title: this.$t('Restart'),
				message: this.$t('Are you sure you want to restart the server? The server will be temporarily unavailable during the restart process.'),
				primaryAction: {
					label: this.$t('Confirm'),
					onClick: ({ hide }) => {
						// 立即显示成功提示并关闭弹窗
						toast.success(this.$t('Restart request submitted'));
						hide();
						
						// 异步提交请求
						this.restartLoading = true;
						const restartRequest = createResource({
							url: '/api/action/jcloud.api.aliyun_server_light.reboot_aliyun_instance',
							params: {
								instance_id: this.$jsiteServer.pg.instance_id,
								region_id: this.$jsiteServer.pg.region
							},
							onSuccess: () => {
								this.restartLoading = false;
							},
							onError: (error) => {
								toast.error(getToastErrorMessage(error));
								this.restartLoading = false;
							}
						});
						restartRequest.submit();
					}
				}
			});
		},
		async forceRestartServer() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			confirmDialog({
				title: this.$t('Force Restart'),
				message: this.$t('Are you sure you want to force restart the server? This operation may cause unsaved data loss.'),
				primaryAction: {
					label: this.$t('Confirm'),
					onClick: ({ hide }) => {
						toast.success(this.$t('Force restart request submitted'));
						hide();
						this.forceRestartLoading = true;
						const req = createResource({
							url: '/api/action/jcloud.api.aliyun_server_light.force_reboot_aliyun_instance',
							params: {
								instance_id: this.$jsiteServer.pg.instance_id,
								region_id: this.$jsiteServer.pg.region
							},
							onSuccess: () => {
								this.forceRestartLoading = false;
							},
							onError: (error) => {
								toast.error(getToastErrorMessage(error));
								this.forceRestartLoading = false;
							}
						});
						req.submit();
					}
				}
			});
		},
		async resetPassword() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			// 弹出密码输入对话框
			const PasswordDialog = defineAsyncComponent(() => import('../dialogs/PasswordDialog.vue'));
			
			renderDialog(h(PasswordDialog, {
				title: this.$t('Reset Server Password'),
				description: this.$t('Length must be between 8 and 30 characters, and must include uppercase and lowercase letters, numbers, and special characters.'),
				onConfirm: (password) => {
					// 立即显示成功提示
					toast.success(this.$t('Password reset request submitted'));
					
					// 异步提交请求
					this.resetPasswordLoading = true;
					const resetPasswordRequest = createResource({
						url: '/api/action/jcloud.api.aliyun_server_light.reset_aliyun_instance_password',
						params: {
							instance_id: this.$jsiteServer.pg.instance_id,
							password: password,
							region_id: this.$jsiteServer.pg.region
						},
						onSuccess: () => {
							this.resetPasswordLoading = false;
						},
						onError: (error) => {
							toast.error(getToastErrorMessage(error));
							this.resetPasswordLoading = false;
						}
					});
					resetPasswordRequest.submit();
				}
			}));
		},
		async resetKeyPair() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			confirmDialog({
				title: this.$t('Reset Key Pair'),
				message: this.$t('Are you sure you want to reset the key pair? This will delete the old key pair and create a new one. After resetting, you will need to use the new private key to connect to the server.'),
				primaryAction: {
					label: this.$t('Confirm'),
					onClick: ({ hide }) => {
						// 立即显示成功提示并关闭弹窗
						toast.success(this.$t('Key pair reset request submitted'));
						hide();
						
						// 异步提交请求
						this.resetKeyPairLoading = true;
						const resetKeyPairRequest = createResource({
							url: '/api/action/jcloud.api.aliyun_server_light.reset_server_key_pair',
							params: {
								instance_id: this.$jsiteServer.pg.instance_id
							},
							onSuccess: () => {
								this.resetKeyPairLoading = false;
							},
							onError: (error) => {
								toast.error(getToastErrorMessage(error));
								this.resetKeyPairLoading = false;
							}
						});
						resetKeyPairRequest.submit();
					}
				}
			});
		},
		async deleteKeyPair() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			confirmDialog({
				title: this.$t('Delete Key Pair'),
				message: this.$t('Are you sure you want to delete the key pair? After deletion, you will not be able to connect to the server using the private key. It is recommended to set a server password first.'),
				primaryAction: {
					label: this.$t('Confirm'),
					onClick: ({ hide }) => {
						// 立即显示成功提示并关闭弹窗
						toast.success(this.$t('Key pair deletion request submitted'));
						hide();
						
						// 异步提交请求
						this.deleteKeyPairLoading = true;
						const deleteKeyPairRequest = createResource({
							url: '/api/action/jcloud.api.aliyun_server_light.delete_aliyun_instance_key_pair',
							params: {
								instance_id: this.$jsiteServer.pg.instance_id
							},
							onSuccess: () => {
								this.deleteKeyPairLoading = false;
								// 刷新服务器数据以更新界面
								this.$jsiteServer.reload();
							},
							onError: (error) => {
								toast.error(getToastErrorMessage(error));
								this.deleteKeyPairLoading = false;
							}
						});
						deleteKeyPairRequest.submit();
					}
				}
			});
		},
		async resetSystem() {
			if (!this.$jsiteServer.pg.instance_id) {
				toast.error(this.$t('Server instance ID does not exist'));
				return;
			}
			
			confirmDialog({
				title: this.$t('Reset System'),
				message: this.$t('Are you sure you want to reset the system? This will clear all data and reinstall the system. This operation is irreversible!'),
				primaryAction: {
					label: this.$t('Confirm'),
					onClick: ({ hide }) => {
						// 立即显示成功提示并关闭弹窗
						toast.success(this.$t('System reset request submitted'));
						hide();
						
						// 异步提交请求
						this.resetSystemLoading = true;
						const resetSystemRequest = createResource({
							url: '/api/action/jcloud.api.aliyun_server_light.reset_aliyun_instance_system',
							params: {
								instance_id: this.$jsiteServer.pg.instance_id,
								region_id: this.$jsiteServer.pg.region
							},
							onSuccess: () => {
								this.resetSystemLoading = false;
							},
							onError: (error) => {
								toast.error(getToastErrorMessage(error));
								this.resetSystemLoading = false;
							}
						});
						resetSystemRequest.submit();
					}
				}
			});
		},
		togglePassword() {
			if (this.showPassword) {
				this.showPassword = false;
				this.decryptedPassword = null;
			} else {
				const getPasswordRequest = createResource({
					url: '/api/action/jcloud.api.aliyun_server_light.get_password',
					params: {
						pagetype: 'Jsite Server',
						name: this.$jsiteServer.pg.name,
						fieldname: 'password'
					},
					onSuccess: (response) => {
						if (response && response !== '') {
							this.decryptedPassword = response;
							this.showPassword = true;
						} else {
							toast.warning(this.$t('No password is currently saved'));
						}
					},
					onError: (error) => {
						toast.error(this.$t('Failed to get password'));
					}
				});
				getPasswordRequest.submit();
			}
		},
		copyPrivateKey() {
			if (this.$jsiteServer.pg.private_key) {
				navigator.clipboard.writeText(this.$jsiteServer.pg.private_key).then(() => {
					this.copySuccess = true;
					toast.success(this.$t('Private key copied to clipboard'));
					setTimeout(() => {
						this.copySuccess = false;
					}, 2000);
				}).catch(() => {
					toast.error(this.$t('Copy failed, please copy manually'));
				});
			}
		},
		onRenewalSuccess(data) {
			toast.success(this.$t('Server renewal successful!'));
			// 刷新服务器数据
			this.$jsiteServer.reload();
		},
		onUpgradeSuccess(data) {
			toast.success(this.$t('Server upgrade successful!'));
			// 刷新服务器数据
			this.$jsiteServer.reload();
		},
		startEditServerName() {
			this.editServerNameValue = this.$jsiteServer.pg?.title || this.$jsiteServer.pg?.name || '';
			this.editingServerName = true;
			this.$nextTick(() => {
				const input = this.$refs.serverNameInput;
				if (input && typeof input.focus === 'function') {
					input.focus();
					if (typeof input.select === 'function') {
						input.select();
					}
				}
			});
		},
		cancelEditServerName() {
			this.editingServerName = false;
			this.editServerNameValue = '';
		},
		handleInputBlur() {
			// 延迟处理，防止点击按钮时触发
			setTimeout(() => {
				if (this.editingServerName && !this.saveServerNameLoading) {
					this.saveServerName();
				}
			}, 150);
		},
		async saveServerName() {
			if (this.saveServerNameLoading) return;
			
			const newName = this.editServerNameValue.trim();
			if (!newName) {
				toast.error(this.$t('Server name cannot be empty'));
				return;
			}
			
			if (newName.length < 2) {
				toast.error(this.$t('Server name must be at least 2 characters'));
				return;
			}
			
			if (newName.length > 100) {
				toast.error(this.$t('Server name cannot exceed 100 characters'));
				return;
			}
			
			if (newName === (this.$jsiteServer.pg?.title || this.$jsiteServer.pg?.name)) {
				this.cancelEditServerName();
				return;
			}
			
			this.saveServerNameLoading = true;
			
			try {
				this.$jsiteServer.setValue.submit(
					{ title: newName },
					{
						onSuccess: () => {
							toast.success(this.$t('Server name updated'));
							this.editingServerName = false;
							this.editServerNameValue = '';
							this.saveServerNameLoading = false;
						},
						onError: (error) => {
							toast.error(getToastErrorMessage(error));
							this.saveServerNameLoading = false;
						}
					}
				);
			} catch (error) {
				toast.error(this.$t('Update failed, please try again'));
				this.saveServerNameLoading = false;
			}
		},
	},
	computed: {
		serverInformation() {
			return [
				{
					label: this.$t('Status'),
					value: this.getStatusText(this.$jsiteServer.pg?.status),
				},				
				{
					label: this.$t('Server Name'),
					value: this.$jsiteServer.pg?.title || this.$jsiteServer.pg?.name,
				},
				{
					label: this.$t('Instance ID'),
					value: this.$jsiteServer.pg?.instance_id || '',
				},
				{
					label: this.$t('Public IP'),
					value: this.$jsiteServer.pg?.public_ip || '',
				},
				{
					label: this.$t('Private IP'),
					value: this.$jsiteServer.pg?.private_ip || '',
				},
				{
					label: this.$t('Region'),
					value: this.getRegionText(this.$jsiteServer.pg?.region),
				},
				{
					label: this.$t('System'),
					value: this.$jsiteServer.pg?.system || '',
				},
			];
		},
		$jsiteServer() {
			return getCachedDocumentResource('Jsite Server', this.server);
		},
	},
};
</script> 