import { createElement, useEffect, forwardRef } from "react";
import { Form, useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { PatternFormat } from "react-number-format";
import clsx from "clsx";
import { z } from "zod";

const N8N_URL = "https://n8n.eduseg.com.br/webhook/eduseg";

const schema = z.object({
  name: z.string().nonempty({ message: "Deve preencher o nome" }),
  email: z
    .string()
    .nonempty({ message: "Deve preencher o email" })
    .email({ message: "Deve ser um email válido" }),
  telephone: z.string().nonempty({ message: "Deve preencher o telefone" }),
  orgname: z.string().nonempty({ message: "Deve preencher a empresa" }),
  message: z.string().nonempty({ message: "Deve preencher a mensagem" }),
});

export default function Contact({ url }) {
  const { register, formState, control, reset, setValue } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      telephone: "",
    },
  });

  useEffect(() => {
    const handler = (e) => {
      setValue("solution", e.detail);
    };

    window.addEventListener("custom_event:react_form", handler);

    return () => {
      window.removeEventListener("custom_event:react_form", handler);
    };
  }, [setValue]);

  return (
    <Form
      action={N8N_URL}
      onSuccess={() => reset()}
      control={control}
      className="flex flex-col gap-3"
    >
      {formState.isSubmitSuccessful && (
        <p className="border border-lime-400 text-white bg-lime-400/25 p-5 rounded-xl font-semibold">
          Sua mensagem foi enviada com sucesso.
        </p>
      )}

      <input type="hidden" {...register("solution")} />
      <input type="hidden" defaultValue={url} {...register("url")} />

      <Control>
        <Input
          aria-invalid={!!formState.errors?.name}
          placeholder="Digite seu nome"
          autoFocus={true}
          {...register("name")}
        />
        <Error>{formState.errors.name?.message}</Error>
      </Control>

      <Control>
        <Input
          aria-invalid={!!formState.errors?.name}
          placeholder="Email corporativo"
          {...register("email")}
        />
        <Error>{formState.errors.email?.message}</Error>
      </Control>

      <Control>
        <Controller
          control={control}
          name="telephone"
          defaultValue=""
          render={({ field: { ref, ...props } }) => {
            return (
              <Input
                aria-invalid={!!formState.errors?.name}
                as={PatternFormat}
                placeholder="Telefone"
                format="+55 (##) ### ### ###"
                getInputRef={ref}
                mask="_"
                {...props}
              />
            );
          }}
        />
        <Error>{formState.errors.telephone?.message}</Error>
      </Control>

      <Control>
        <Input
          aria-invalid={!!formState.errors?.name}
          placeholder="Empresa"
          {...register("orgname")}
        />
        <Error>{formState.errors.orgname?.message}</Error>
      </Control>

      <Control>
        <Input
          as="textarea"
          className="h-28"
          placeholder="Mensagem"
          aria-invalid={!!formState.errors?.message}
          {...register("message")}
        />
        <Error>{formState.errors.message?.message}</Error>
      </Control>

      <button
        type="submit"
        className="p-2.5 border border-lime-400 rounded-lg cursor-pointer disabled:border-white/10 disabled:pointer-events-none relative overflow-hidden group"
        disabled={formState.isSubmitting}
      >
        <div className="absolute inset-0 hidden group-disabled:flex items-center justify-center bg-black">
          <Spinner className="size-6 animate-spin" />
        </div>
        <>Enviar</>
      </button>
    </Form>
  );
}

export const Input = forwardRef(function Input(
  { as = "input", className, children, ...props },
  ref,
) {
  return createElement(
    as,
    {
      className: clsx(
        "bg-white/10 focus:bg-white/15 rounded-lg p-3 w-full border border-white/10 focus:border-lime-400 focus:outline-0 transition appearance-none ",
        "placeholder-white/70",
        "disabled:bg-white/5 disabled:text-white/30",
        "aria-invalid:border-red-600",
        className,
      ),
      ref,
      ...props,
    },
    children,
  );
});

function Control({ children, className }) {
  return <label className={className}>{children}</label>;
}

function Error({ children, className }) {
  if (children) {
    return (
      <p className={clsx("text-sm text-red-400", className)}>{children}</p>
    );
  }

  return null;
}

function Spinner(props) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
      {...props}
    >
      <circle
        className="opacity-25"
        cx="12"
        cy="12"
        r="10"
        stroke="currentColor"
        strokeWidth="4"
      ></circle>
      <path
        className="opacity-75"
        fill="currentColor"
        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
      ></path>
    </svg>
  );
}
