import toast from "react-hot-toast";
import { z } from "zod/v4";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "~/components/custom_ui/form";
import { DualInputLayout } from "~/components/custom_ui/inputLayouts";
import { Button } from "~/components/ui/button";
import Input from "~/components/ui/input";
import { PhoneInput } from "~/components/ui/phone-input";
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"
	| "extra_telefono_numero"
	| "extra_telefono_titolo"
> &
	Partial<Pick<Users, "isAdmin">>;

export const ProfileFormAccount = ({
	id,
	nome,
	cognome,
	email,
	telefono,
	extra_telefono_numero,
	extra_telefono_titolo,
	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"),
		extra_telefono_numero: z.string().optional(),
		extra_telefono_titolo: z.string().optional(),
	});

	type ProfileFormValues = z.infer<typeof profileFormSchema>;

	const defaultValues: ProfileFormValues = {
		cognome: cognome || "",
		email: email,
		isAdmin: isAdmin,
		nome: nome || "",
		telefono,
		extra_telefono_numero: extra_telefono_numero || "",
		extra_telefono_titolo: extra_telefono_titolo || "",
	};
	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, ""),
				extra_telefono_numero: fields.extra_telefono_numero?.replace(/\s/g, ""),
				username: `${fields.cognome?.trim()} ${fields.nome?.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}
												autoComplete="off"
												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}
												autoComplete="off"
												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
												autoComplete="off"
												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} autoComplete="off" id="telefono" />
										</FormControl>
									</FormItem>
								)}
							/>
						}
					/>
					<DualInputLayout
						children1={
							<FormField
								control={form.control}
								name="extra_telefono_numero"
								render={({ field }) => (
									<FormItem>
										<div className="flex flex-wrap items-center gap-x-2">
											<FormLabel htmlFor="extra_telefono_numero">
												{t.profile.extra_telefono_numero}
											</FormLabel>
											<FormMessage />
										</div>

										<FormControl>
											<PhoneInput
												{...field}
												autoComplete="off"
												id="extra_telefono_numero"
											/>
										</FormControl>
									</FormItem>
								)}
							/>
						}
						children2={
							<FormField
								control={form.control}
								name="extra_telefono_titolo"
								render={({ field }) => (
									<FormItem>
										<div className="flex flex-wrap items-center gap-x-2">
											<FormLabel htmlFor="extra_telefono_titolo">
												{t.profile.extra_telefono_titolo}
											</FormLabel>
											<FormMessage />
										</div>

										<FormControl>
											<Input
												placeholder=""
												{...field}
												autoComplete="off"
												id="extra_telefono_titolo"
											/>
										</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"
												name="isAdmin"
												onCheckedChange={(v) => {
													field.onChange(v);
												}}
											/>
										</FormControl>
										<FormMessage />
									</div>
								</FormItem>
							)}
						/>
					)}

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