import { z } from "zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import Input from "~/components/custom_ui/input";
import { Textarea } from "~/components/custom_ui/textarea";
import { customErrorMapWrapper } from "~/hooks/locale";
import { useZodForm } from "~/lib/zodForm";
import { api } from "~/utils/api";
import { useTranslation } from "~/providers/I18nProvider";
import { CheckCircle } from "lucide-react";
import { useState } from "react";
import { Checkbox } from "~/components/ui/checkbox";
import toast from "react-hot-toast";
import { useLocalStorage } from "react-use";
import { PhoneInput } from "~/components/phone-input";

type UserContattoData = {
  nome: string;
  email: string;
  telefono: string;
};

export const FormContattoAnnucio = ({ codice }: { codice: string }) => {
  const { locale, t } = useTranslation();
  const [hasSent, setHasSent] = useState(false);
  const schema = z.object({
    nome: z.string().nonempty("Inserisci un nome valido"),

    email: z.string().email(),
    messaggio: z.string().nonempty("Inserisci un messaggio"),
    telefono: z.string().nonempty("Inserisci un numero di telefono"),
    checkbox: z.boolean().refine((val) => val === false), // Honeypot field
  });
  const [value, setValue] = useLocalStorage<UserContattoData>(
    "infoalloggi-user-contatto",
    {
      nome: "",
      email: "",
      telefono: "",
    },
  );

  type FromValues = z.infer<typeof schema>;
  const form = useZodForm({
    schema: schema,
    defaultValues: {
      ...value,
      messaggio: "",
      checkbox: false, // Honeypot field
    },
  });

  const { mutate } = api.servizio.sendContattoEmail.useMutation({
    onMutate: () => {
      toast.loading("Invio in corso...", {
        id: "contatto",
      });
    },
    onSuccess: (data) => {
      setHasSent(true);
      form.reset();
      toast.success(
        "Email inviata correttamente, ti contatteremo al più presto",
        {
          id: "contatto",
        },
      );
      setValue({
        ...data,
      });
    },
    onError: (error) => {
      console.error(error);
      toast.error("Errore durante l'invio dell'email", {
        id: "contatto",
      });
    },
  });
  const onSubmit = (data: FromValues) => {
    mutate({
      ...data,
      telefono: data.telefono.replace(/\s/g, ""), // Remove spaces from phone number
      codice,
    });
  };
  z.setErrorMap(customErrorMapWrapper(locale));

  return (
    <div className="mx-auto w-full">
      {hasSent ? (
        <div className="flex h-full w-full items-center justify-center pt-14">
          <div className="mx-auto max-w-lg space-y-3 text-center">
            <CheckCircle className="mx-auto size-20 text-green-600" />
            <h3 className="text-accent-foreground text-4xl font-semibold sm:text-5xl">
              Successo
            </h3>
            <p className="text-neutral-600">Email inviata correttamente</p>
            <div className="flex flex-wrap items-center justify-center gap-3"></div>
          </div>
        </div>
      ) : (
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-8 px-0.5"
          >
            <FormField
              control={form.control}
              name="nome"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="nome">{t.contact_form.nome}</FormLabel>
                    <FormMessage />
                  </div>
                  <FormControl>
                    <Input {...field} type="text" />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="email">
                      {t.contact_form.email}
                    </FormLabel>
                    <FormMessage />
                  </div>
                  <FormControl>
                    <Input {...field} type="email" />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="telefono"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="telefono">
                      {t.contact_form.telefono}
                    </FormLabel>
                    <FormMessage />
                  </div>
                  <FormControl>
                    <PhoneInput {...field} id="telefono" />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="messaggio"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="messaggio">
                      {t.contact_form.messaggio}
                    </FormLabel>
                    <FormMessage />
                  </div>
                  <FormControl>
                    <Textarea className="min-h-[150px]" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="checkbox"
              render={({ field }) => (
                <FormItem className="hidden">
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="checkbox">Check Me</FormLabel>
                    <FormMessage />
                  </div>

                  <FormControl>
                    <Checkbox
                      id="checkbox"
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            <button className="w-full rounded-lg bg-neutral-600 px-4 py-2 font-medium text-white duration-150 hover:bg-neutral-500 active:bg-neutral-600">
              {t.contact_form.invia}
            </button>
          </form>
        </Form>
      )}
    </div>
  );
};
