"use client"; import { useState } from 'react'; import { z } from 'zod'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { useToast } from '@/hooks/use-toast'; import { Loader2 } from 'lucide-react'; // Define the form schema const formSchema = z.object({ domain: z.string() .min(3, { message: 'Domain must be at least 3 characters' }) .regex(/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/, { message: 'Please enter a valid domain name (e.g., example.com)', }), serverIp: z.string() .regex(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/, { message: 'Please enter a valid IPv4 address', }), }); type FormValues = z.infer; interface AddDomainDialogProps { open: boolean; onOpenChange: (open: boolean) => void; apiKey: string; onDomainAdded: (domain: { domain: string; date_created: string }) => void; } export function AddDomainDialog({ open, onOpenChange, apiKey, onDomainAdded }: AddDomainDialogProps) { const [isSubmitting, setIsSubmitting] = useState(false); const { toast } = useToast(); const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { domain: '', serverIp: '', }, }); const onSubmit = async (values: FormValues) => { try { setIsSubmitting(true); const response = await fetch('/api/vultr/domains', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey, }, body: JSON.stringify({ domain: values.domain, serverip: values.serverIp, }), }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Failed to add domain'); } const data = await response.json(); onDomainAdded(data.domain); form.reset(); } catch (error) { console.error('Error adding domain:', error); toast({ title: 'Error', description: error instanceof Error ? error.message : 'Failed to add domain', variant: 'destructive', }); } finally { setIsSubmitting(false); } }; return ( Add New Domain Enter the domain name and server IP address to add a new domain to your Vultr account.
( Domain Name )} /> ( Server IP Address )} />
); }