'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' import { Header } from '@/components/header' import { Footer } from '@/components/footer' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { Checkbox } from '@/components/ui/checkbox' import { Alert, AlertDescription } from '@/components/ui/alert' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Cloud, Server, HardDrive, Shield, AlertCircle, Check, Cpu, MapPin, ExternalLink, Terminal, } from 'lucide-react' import { useAuth } from '@/contexts/AuthContext' import { checkSufficientBalance, formatCurrency } from '@/lib/balance-service' interface Plan { id: string name: string price: { daily: number monthly: number } } interface OSImage { id: string name: string price?: { daily: number monthly: number } } interface DataCenter { id: string name: string } interface DeploymentResult { status: string cloudid?: string message?: string password?: string ipv4?: string server_id?: string error?: string [key: string]: any } export default function CloudInstancePage() { const router = useRouter() const { user } = useAuth() const [loading, setLoading] = useState(false) const [error, setError] = useState('') const [success, setSuccess] = useState('') const [deploymentResult, setDeploymentResult] = useState(null) const [billingCycle, setBillingCycle] = useState<'daily' | 'monthly'>('monthly') // Form state const [formData, setFormData] = useState({ hostname: '', planId: '', image: '', password: '', dcslug: '', enableBackup: false, enablePublicIp: true, }) // Available plans const plans: Plan[] = [ { id: '10027', name: '2 vCPU, 4GB RAM, 80GB SSD', price: { daily: 60, monthly: 1600 } }, { id: '10028', name: '4 vCPU, 8GB RAM, 160GB SSD', price: { daily: 80, monthly: 2200 } }, { id: '10029', name: '8 vCPU, 32GB RAM, 480GB SSD', price: { daily: 100, monthly: 2800 } }, { id: '10030', name: '16 vCPU, 64GB RAM, 960GB SSD', price: { daily: 120, monthly: 3200 } }, ] // Available OS images const images: OSImage[] = [ { id: 'almalinux-9.2-x86_64', name: 'Alma Linux 9.2' }, { id: 'centos-7.9-x86_64', name: 'CentOS 7.9' }, { id: 'debian-12-x86_64', name: 'Debian 12' }, { id: 'ubuntu-22.04-x86_64', name: 'Ubuntu 22.04 LTS' }, { id: 'windows-2022', name: 'Windows Server 2022', price: { daily: 200, monthly: 5000 } }, ] // Data centers const dataCenters: DataCenter[] = [ { id: 'inmumbaizone2', name: 'Mumbai, India' }, { id: 'inbangalore', name: 'Bangalore, India' }, ] // Get user balance from auth context const userBalance = user?.balance || 0 // Calculate total price const calculatePrice = () => { const selectedPlan = plans.find((p) => p.id === formData.planId) const selectedImage = images.find((i) => i.id === formData.image) if (!selectedPlan) return 0 let total = selectedPlan.price[billingCycle] // Add Windows license cost if applicable if (selectedImage?.price) { total += selectedImage.price[billingCycle] } // Add backup cost (20% of plan price) if (formData.enableBackup) { total += selectedPlan.price[billingCycle] * 0.2 } return total } const handleDeploy = async (e: React.FormEvent) => { e.preventDefault() setError('') setSuccess('') setDeploymentResult(null) if (!user) { router.push('/auth?redirect=/services/cloud-instance') return } // Validate form if ( !formData.hostname || !formData.planId || !formData.image || !formData.password || !formData.dcslug ) { setError('All fields are required') return } // Check password strength if (formData.password.length < 8) { setError('Password must be at least 8 characters long') return } // Check balance const totalPrice = calculatePrice() const balanceCheck = await checkSufficientBalance(totalPrice) if (!balanceCheck.sufficient) { setError( balanceCheck.error || `Insufficient balance. You need ${formatCurrency(totalPrice)} but only have ${formatCurrency(balanceCheck.currentBalance || 0)}` ) return } setLoading(true) try { const response = await fetch('/api/services/deploy-cloude', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ hostname: formData.hostname, planid: formData.planId, image: formData.image, dclocation: formData.dcslug, password: formData.password, cycle: billingCycle, amount: totalPrice, backup: formData.enableBackup, publicip: formData.enablePublicIp, }), }) const result: DeploymentResult = await response.json() if (!response.ok) { throw new Error(result.message || `Deployment failed with status ${response.status}`) } if (result.status === 'success') { setDeploymentResult(result) // Create success message with server details let successMessage = 'Cloud instance deployed successfully!' if (result.cloudid) { successMessage += ` Server ID: ${result.cloudid}` } if (result.ipv4) { successMessage += ` | IP: ${result.ipv4}` } setSuccess(successMessage) // Reset form after successful deployment setFormData({ hostname: '', planId: '', image: '', password: '', dcslug: '', enableBackup: false, enablePublicIp: true, }) } else { throw new Error(result.message || 'Deployment failed') } } catch (err) { console.error('Deployment error:', err) setError(err instanceof Error ? err.message : 'Failed to deploy cloud instance') } finally { setLoading(false) } } const resetForm = () => { setDeploymentResult(null) setSuccess('') setError('') } return (
{/* Page Header */}

Deploy Cloud Instance

High-performance cloud servers with instant deployment

{!user && ( You need to be logged in to deploy a cloud instance.{' '} Click here to login )} {success && (
{success}
{deploymentResult?.ipv4 && (

{deploymentResult.cloudid || deploymentResult.server_id}

)} {deploymentResult?.password && (

Please change this password after first login

)} {deploymentResult?.message && (

{deploymentResult.message}

)}

✅ Deployment successful! Your server is being provisioned.

{/*

📧 Login details will be sent to your email once ready.

*/}
)} {deploymentResult ? ( Deployment Successful! Your cloud instance has been deployed successfully.

{deploymentResult.server_id}

{deploymentResult.status}

) : (
{/* Billing Cycle Selection */} Billing Cycle Choose your preferred billing period setBillingCycle(v as 'daily' | 'monthly')} > Daily Monthly (Save 20%) {/* Server Configuration */} Server Configuration Configure your cloud instance specifications
setFormData({ ...formData, hostname: e.target.value })} required />
setFormData({ ...formData, password: e.target.value })} required />

Minimum 8 characters required

setFormData({ ...formData, enableBackup: checked as boolean }) } />
setFormData({ ...formData, enablePublicIp: checked as boolean }) } />
{/* Pricing Summary */} Order Summary
Base Plan ₹{plans.find((p) => p.id === formData.planId)?.price[billingCycle] || 0}
{images.find((i) => i.id === formData.image)?.price && (
Windows License ₹ {images.find((i) => i.id === formData.image)?.price?.[billingCycle] || 0}
)} {formData.enableBackup && (
Backup Service ₹ {(plans.find((p) => p.id === formData.planId)?.price[billingCycle] || 0) * 0.2}
)}
Total ₹{calculatePrice()}/{billingCycle === 'daily' ? 'day' : 'month'}
Your Balance = calculatePrice() ? 'text-green-600' : 'text-red-600' } > ₹{userBalance.toFixed(2)}
{error && ( {error} )} {/* Deploy Button */}
)} {/* Features */} {!deploymentResult && (
High Performance

Enterprise-grade hardware with NVMe SSD storage

Secure & Reliable

DDoS protection and 99.99% uptime SLA

Instant Deployment

Your server ready in less than 60 seconds

)}
) } // jRIfuQspDJlWdgXxLmqVFSUthwBOkezibPCyoTvHYcEANraGKMnZ // { // "status": "success", // "cloudid": "1645972", // "message": "Cloud Server deploy in process and as soon it get ready to use system will send you login detail over the email.", // "password": "00000000", // "ipv4": "103.189.89.32" // }