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

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({
		cognome: z.string().nonempty("Inserisci un cognome valido"),
		email: z.email(),
		isAdmin: z.boolean().optional(),
		nome: z.string().nonempty("Inserisci un nome valido"),
		telefono: z.string().nonempty("Inserisci un numero di telefono"),
	});

	type ProfileFormValues = z.infer<typeof profileFormSchema>;

	const defaultValues: ProfileFormValues = {
		cognome: cognome || "",
		email: email,
		isAdmin: isAdmin,
		nome: nome || "",
		telefono,
	};
	const { locale, t } = useTranslation();
	z.config(z.locales[locale]());

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

	const utils = api.useUtils();

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

	function onSubmit(fields: ProfileFormValues) {
		mutate({
			id,
			data: {
				...fields,
				telefono: fields.telefono?.replace(/\s/g, ""),
				username: `${fields.nome?.trim()} ${fields.cognome?.trim()}`,
				isAdmin: fields.isAdmin || false,
			},
		});
	}

	return (
		<>
			<Form {...form}>
				<form
					className="space-y-8 px-0.5"
					onSubmit={form.handleSubmit(onSubmit)}
				>
					<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
												className="data-[state=checked]:bg-neutral-700"
												defaultChecked={field.value}
												id="isAdmin"
												onCheckedChange={(v) => {
													field.onChange(v);
												}}
											/>
										</FormControl>
										<FormMessage />
									</div>
								</FormItem>
							)}
						/>
					)}

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