import type { NextPage } from "next";
import Head from "next/head";
import Link from "next/link";
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 { DualInputLayout } from "~/components/custom_ui/inputLayouts";
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";

const Contatto: NextPage = () => {
  const { locale, t } = useTranslation();
  const [hasSent, setHasSent] = useState(false);
  const ContactFormSchema = z.object({
    nome: z.string().nonempty("Inserisci un nome valido"),
    cognome: z.string().nonempty("Inserisci un cognome valido"),
    email: z.string().email(),
    messaggio: z.string().nonempty("Inserisci un messaggio"),
    numero: z.string().nonempty("Inserisci un numero di telefono"),
    checkbox: z.boolean().refine((val) => val === false), // Honeypot field
  });

  const form = useZodForm({
    schema: ContactFormSchema,
    defaultValues: {
      nome: "",
      cognome: "",
      email: "",
      messaggio: "",
      numero: "",
      checkbox: false, // Honeypot field
    },
  });

  const { mutate: contactMutation } = api.contact.postContact.useMutation({
    onSuccess: () => {
      setHasSent(true);
      form.reset();
    },
  });
  const onSubmit = (data: z.infer<typeof ContactFormSchema>) => {
    contactMutation({
      nome: data.nome,
      cognome: data.cognome,
      email: data.email,
      messaggio: data.messaggio,
      telefono: data.numero,
    });
  };
  z.setErrorMap(customErrorMapWrapper(locale));

  return (
    <>
      <Head>
        <title>{t.heads.contatti_titolo}</title>
        <meta name="description" content={t.heads.main_description} />
      </Head>
      <main className="mx-auto w-full max-w-6xl px-2 py-5 md:px-8">
        <div className="bg-primary/10 text-primary inline-block rounded-lg px-3 py-1 text-sm">
          {t.contatti}
        </div>

        <div className="mx-auto max-w-screen-xl px-4 text-neutral-600 md:px-8">
          <div className="mx-auto max-w-lg space-y-3 sm:text-center">
            <p className="text-accent-foreground text-4xl font-semibold">
              {t.contact_form.titolo}
            </p>
            <p>
              {t.contact_form.sottotitolo1}{" "}
              <Link href="/guida#faq">
                <span className="text-accent-foreground text-lg font-bold">
                  {t.contact_form.sottotitolo2}
                </span>
              </Link>{" "}
              {t.contact_form.sottotitolo3}
            </p>
          </div>
          <div className="mx-auto mt-12 max-w-xl">
            {hasSent ? (
              <ContactSuccess />
            ) : (
              <Form {...form}>
                <form
                  onSubmit={form.handleSubmit(onSubmit)}
                  className="space-y-8 px-0.5"
                >
                  <DualInputLayout
                    children1={
                      <FormField
                        control={form.control}
                        name="nome"
                        render={({ field }) => (
                          <FormItem>
                            <div className="flex flex-wrap items-center gap-x-2">
                              <FormLabel className="text-base font-medium">
                                {t.contact_form.nome}
                              </FormLabel>
                              <FormMessage />
                            </div>
                            <FormControl>
                              <Input {...field} type="text" />
                            </FormControl>
                          </FormItem>
                        )}
                      />
                    }
                    children2={
                      <FormField
                        control={form.control}
                        name="cognome"
                        render={({ field }) => (
                          <FormItem>
                            <div className="flex flex-wrap items-center gap-x-2">
                              <FormLabel className="text-base font-medium">
                                {t.contact_form.cognome}
                              </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 className="text-base font-medium">
                            {t.contact_form.email}
                          </FormLabel>
                          <FormMessage />
                        </div>
                        <FormControl>
                          <Input {...field} type="email" />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel className="text-base font-medium">
                            {t.contact_form.telefono}
                          </FormLabel>
                          <FormMessage />
                        </div>
                        <FormControl>
                          <Input
                            placeholder="+39 1234567890"
                            {...field}
                            type="text"
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="messaggio"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel className="text-base font-medium">
                            {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>
        </div>
      </main>
    </>
  );
};

export default Contatto;

const ContactSuccess = () => {
  const { t } = useTranslation();
  return (
    <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">
          {t.contact_form.successo}
        </h3>
        <p className="text-neutral-600">{t.contact_form.inviata}</p>
        <div className="flex flex-wrap items-center justify-center gap-3">
          <Link
            aria-label={t.contact_form.cta}
            href="/"
            className="block rounded-lg border px-4 py-2 font-medium text-neutral-700 duration-150 hover:bg-neutral-50 active:bg-neutral-100"
          >
            {t.contact_form.cta}
          </Link>
        </div>
      </div>
    </div>
  );
};
