import { z } from "zod";

import { UseFormReturn } from "react-hook-form";

import { Stepper } from "@stepperize/react";

import { cn } from "@/lib/utils";

import { createAgentSchema } from "../schemas/create-agent-schema";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

import Spinner from "@/components/spinner";

type AgentFormProps = {
  stepper: Stepper<
    {
      id: string;
      title: string;
      description: string;
    }[]
  >;
  form: UseFormReturn<z.infer<typeof createAgentSchema>, any, undefined>;
  onSubmit: (values: z.infer<typeof createAgentSchema>) => void;
  isPending: boolean;
};

export default function AgentForm(props: AgentFormProps) {
  const { stepper, form, onSubmit, isPending } = props;

  const handleSubmit = (values: z.infer<typeof createAgentSchema>) => {
    onSubmit(values);
  };

  const {
    formState: { errors },
  } = form;

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-3">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Agent Name</FormLabel>
              <FormControl>
                <Input
                  placeholder="astrobot"
                  className={cn(
                    errors.name && "focus-visible:ring-destructive"
                  )}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Description</FormLabel>
              <FormControl>
                <Textarea
                  rows={4}
                  placeholder="For answering daily questions."
                  className={cn(
                    errors.description && "focus-visible:ring-destructive"
                  )}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div>
          <div className="flex justify-end gap-4">
            <Button
              variant="outline"
              onClick={stepper.prev}
              disabled={isPending}
            >
              {isPending && <Spinner className="h-4 w-4 mr-2" />}
              Back
            </Button>
            <Button type="submit" disabled={isPending}>
              {isPending && <Spinner className="h-4 w-4 mr-2" />}
              Next
            </Button>
          </div>
        </div>
      </form>
    </Form>
  );
}
