"use client"; import { useState } from 'react'; import { z } from 'zod'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { Button } from '@/components/ui/button'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form'; import { Input } from '@/components/ui/input'; import { Key, Loader2 } from 'lucide-react'; const formSchema = z.object({ apiKey: z.string().min(1, 'API Key is required'), }); interface ApiKeyFormProps { onApiKeySubmit: (apiKey: string) => void; } export function ApiKeyForm({ onApiKeySubmit }: ApiKeyFormProps) { const [isLoading, setIsLoading] = useState(false); const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { apiKey: '', }, }); async function onSubmit(values: z.infer) { setIsLoading(true); try { // Validate the API key by making a test request const response = await fetch('/api/vultr', { headers: { 'X-API-Key': values.apiKey, }, }); if (response.ok) { onApiKeySubmit(values.apiKey); } else { form.setError('apiKey', { type: 'manual', message: 'Invalid API Key. Please check and try again.', }); } } catch (error) { form.setError('apiKey', { type: 'manual', message: 'Failed to validate API Key. Please try again.', }); } finally { setIsLoading(false); } } return (
( Vultr API Key Your API key can be found in your Vultr account settings. )} />
); }