import { z } from "zod";
import { useZodForm } from "~/lib/zodForm";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import Input from "~/components/custom_ui/input";
import { Button } from "~/components/ui/button";
import toast from "react-hot-toast";
import { customErrorMapWrapper } from "~/hooks/locale";
import { api } from "~/utils/api";
import { useTranslation } from "~/providers/I18nProvider";
import type { Users, UsersId } from "~/schemas/public/Users";
import { DualInputLayout } from "~/components/custom_ui/inputLayouts";
import { PhoneInput } from "~/components/phone-input";
import { Switch } from "~/components/ui/switch";

type ProfileFromAccountProps = Pick<
  Users,
  "id" | "nome" | "cognome" | "email" | "telefono"
> &
  Partial<Pick<Users, "isAdmin">>;

export const ProfileFormAccount = ({
  id,
  nome,
  cognome,
  email,
  telefono,
  isAdmin,
}: ProfileFromAccountProps) => {
  const profileFormSchema = z.object({
    nome: z.string().nonempty("Inserisci un nome valido"),
    cognome: z.string().nonempty("Inserisci un cognome valido"),
    email: z.string().email(),
    telefono: z.string().nonempty("Inserisci un numero di telefono"),
    isAdmin: z.boolean().optional(),
  });

  type ProfileFormValues = z.infer<typeof profileFormSchema>;

  const defaultValues: ProfileFormValues = {
    nome: nome || "",
    cognome: cognome || "",
    email: email,
    telefono,
    isAdmin: isAdmin,
  };
  const { locale, t } = useTranslation();
  z.setErrorMap(customErrorMapWrapper(locale));

  const form = useZodForm({
    schema: profileFormSchema,
    defaultValues: defaultValues,
  });

  const utils = api.useUtils();

  const { mutate } = api.users.editUser.useMutation({
    onSuccess: async () => {
      toast.success(t.profile.aggiornato);
      await utils.auth.getSession.invalidate();
      await utils.users.getUser.invalidate();
      await utils.users.getClientProfilo.invalidate();
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  function onSubmit(fields: ProfileFormValues) {
    const data: {
      id: UsersId;
      email: string;
      isAdmin?: boolean;
      nome: string;
      cognome: string;
      telefono: string;
    } = {
      id: id,
      nome: fields.nome,
      cognome: fields.cognome,
      email: fields.email,
      telefono: fields.telefono.replace(/\s/g, ""),
    };

    if (isAdmin !== undefined) {
      data.isAdmin = fields.isAdmin;
    }
    mutate(data);
  }

  return (
    <>
      <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 htmlFor="nome">{t.profile.nome}</FormLabel>
                      <FormMessage />
                    </div>

                    <FormControl>
                      <Input placeholder="" {...field} id="nome" />
                    </FormControl>
                  </FormItem>
                )}
              />
            }
            children2={
              <FormField
                control={form.control}
                name="cognome"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex flex-wrap items-center gap-x-2">
                      <FormLabel htmlFor="cognome">
                        {t.profile.cognome}
                      </FormLabel>
                      <FormMessage />
                    </div>

                    <FormControl>
                      <Input placeholder="" {...field} id="cognome" />
                    </FormControl>
                  </FormItem>
                )}
              />
            }
          />
          <DualInputLayout
            children1={
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex flex-wrap items-center gap-x-2">
                      <FormLabel htmlFor="email">{t.profile.email}</FormLabel>{" "}
                      <FormMessage />
                    </div>

                    <FormControl>
                      <Input
                        placeholder="esempio@email.com"
                        {...field}
                        id="email"
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
            }
            children2={
              <FormField
                control={form.control}
                name="telefono"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex flex-wrap items-center gap-x-2">
                      <FormLabel htmlFor="telefono">
                        {t.profile.telefono}
                      </FormLabel>
                      <FormMessage />
                    </div>

                    <FormControl>
                      <PhoneInput {...field} id="telefono" />
                    </FormControl>
                  </FormItem>
                )}
              />
            }
          />
          {isAdmin !== undefined && (
            <FormField
              control={form.control}
              name="isAdmin"
              render={({ field }) => (
                <FormItem className="mt-6 flex items-start">
                  <div className="flex items-center justify-center gap-x-4">
                    <FormLabel htmlFor="isAdmin">Admin</FormLabel>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={(v) => {
                          field.onChange(v);
                        }}
                        id="isAdmin"
                        className="data-[state=checked]:bg-neutral-700"
                      />
                    </FormControl>
                    <FormMessage />
                  </div>
                </FormItem>
              )}
            />
          )}

          <Button type="submit">{t.profile.aggiorna}</Button>
        </form>
      </Form>
    </>
  );
};
