import { useForm } from "react-hook-form";
import { useMutation } from "node_modules/@tanstack/react-query/build/legacy";
import { queryClient } from "../queryClient";
import axios from "axios";
import { createElement } from "react";
import clsx from "clsx";

interface IFormInput {
  name: string;
  email: string;
  message: string;
}

export function Form() {
  const { register, handleSubmit, reset, formState } = useForm<IFormInput>();
  const { mutateAsync } = useMutation(
    {
      mutationFn: async (data: IFormInput) => {
        return await axios.post("https://n8n.sergio.run/webhook/eduseg", data);
      },
      onSuccess: () => {
        reset();
      },
    },
    queryClient,
  );

  const onSubmit = async (data: IFormInput) => {
    await mutateAsync(data);
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="flex flex-col gap-3 lg:gap-6"
    >
      {formState.isSubmitSuccessful && (
        <p className="bg-green-700 text-white p-3 rounded-lg">OK!</p>
      )}

      <div className="grid lg:grid-cols-2 gap-3 lg:gap-6">
        <label>
          Nome
          <Input {...register("name")} />
        </label>
        <label>
          Email
          <Input {...register("email")} />
        </label>
      </div>

      <label>
        Mensagem
        <Input as="textarea" className="h-26" {...register("message")} />
      </label>

      <button
        type="submit"
        className="font-medium bg-green-secondary hover:text-black hover:bg-green-support p-3 rounded-lg transition cursor-pointer h-12"
      >
        Quero um orçamento
      </button>
    </form>
  );
}

interface IInput extends React.HTMLAttributes<HTMLElement> {
  as?: string;
  className?: string | undefined;
}

export function Input({ as = "input", className, ...props }: IInput) {
  return createElement(as, {
    className: clsx(
      "border border-transparent focus:border-green-secondary focus:ring ring-green-secondary text-white bg-black p-3 rounded-lg w-full outline-none",
      className,
    ),
    ...props,
  });
}
