"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<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      apiKey: '',
    },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    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 (
    <div className="max-w-md mx-auto">
      <div className="flex justify-center mb-6">
        <div className="bg-primary/10 p-3 rounded-full">
          <Key className="h-6 w-6 text-primary" />
        </div>
      </div>
      
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <FormField
            control={form.control}
            name="apiKey"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Vultr API Key</FormLabel>
                <FormControl>
                  <Input
                    placeholder="Enter your Vultr API key"
                    type="password"
                    autoComplete="off"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  Your API key can be found in your Vultr account settings.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Validating...
              </>
            ) : (
              'Connect to Vultr'
            )}
          </Button>
        </form>
      </Form>
    </div>
  );
}