import { Eye, EyeOff } from "lucide-react";
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 { PhoneInput } from "~/components/phone-input";
import { Button, buttonVariants } from "~/components/ui/button";
import { Switch } from "~/components/ui/switch";
import { useStrongPassword } from "~/hooks/useStrongPassword";
import { generatePassword } from "~/lib/basicPwGenerator";
import { cn } from "~/lib/utils";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { api } from "~/utils/api";

export const FormNewUser = ({
	setOpen,
}: {
	setOpen: (status: boolean) => void;
}) => {
	const {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		toggleVisibility,
	} = useStrongPassword();

	const NewUserSchema = z
		.object({
			cognome: z.string().nonempty("Inserisci un cognome valido"),
			email: z.email(),
			nome: z.string().nonempty("Inserisci un nome valido"),
			password: z.string(),
			telefono: z.string().nonempty("Inserisci un numero di telefono"),
			mustChangePassword: z.boolean(),
		})
		.superRefine(({ password }, refinementContext) => {
			passwordRefine({
				password,
				path: "password",
				refinementContext,
			});
		});
	type NewUserFormValues = z.infer<typeof NewUserSchema>;

	// This can come from your database or API.
	const defaultValues: NewUserFormValues = {
		cognome: "",
		email: "",
		nome: "",
		password: "",
		telefono: "",
		mustChangePassword: true,
	};
	const { locale, t } = useTranslation();

	z.config(z.locales[locale]());

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

	const utils = api.useUtils();

	const { mutate } = api.auth.addUserAdmin.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success(t.newUser.accountCreato);
			await utils.users.getUsersWChatInfo.invalidate();
			await utils.stats.adminDashStats.invalidate();
			setOpen(false);
		},
	});
	function onSubmit(fields: NewUserFormValues) {
		mutate({
			cognome: fields.cognome,
			email: fields.email,
			nome: fields.nome,
			password: fields.password,
			telefono: fields.telefono.replace(/\s/g, ""),
			mustChangePassword: fields.mustChangePassword,
		});
	}

	return (
		<Form {...form}>
			<form className="space-y-8 px-0.5" onSubmit={form.handleSubmit(onSubmit)}>
				<FormField
					control={form.control}
					name="nome"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="nome">{t.newUser.nome}</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input placeholder="" {...field} id="nome" />
							</FormControl>
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="cognome"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="cognome">{t.newUser.cognome}</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input placeholder="" {...field} id="cognome" />
							</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.newUser.email}</FormLabel>{" "}
								<FormMessage />
							</div>
							<FormControl>
								<Input placeholder="esempio@email.com" {...field} id="email" />
							</FormControl>
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="password"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-col gap-x-2">
								<div className="flex items-center justify-between">
									<FormLabel htmlFor="password">
										{t.auth.signup.password}
									</FormLabel>{" "}
									<button
										className={cn(
											buttonVariants({
												size: "sm",
												variant: "outline",
											}),
										)}
										onClick={async () => {
											form.setValue("password", generatePassword());
											await form.trigger("password");
										}}
										type="button"
									>
										genera password
									</button>
								</div>

								<FormMessage
									className={cn(
										"whitespace-pre-wrap",
										getStrengthTxt(strengthScore),
									)}
								/>
							</div>

							<FormControl>
								<div className="relative">
									<Input
										{...field}
										aria-describedby="password-strength"
										aria-invalid={form.getFieldState("password").invalid}
										className="pe-9"
										id="password"
										onChange={async (e) => {
											field.onChange(e);
											await form.trigger("password");
										}}
										placeholder="Password"
										type={isVisible ? "text" : "password"}
									/>
									<button
										aria-controls="password"
										aria-label={isVisible ? "Hide password" : "Show password"}
										aria-pressed={isVisible}
										className="absolute end-0 top-1 flex size-9 items-center justify-center rounded-e-lg text-muted-foreground/80 transition-shadow hover:text-foreground focus-visible:border focus-visible:border-ring focus-visible:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
										onClick={toggleVisibility}
										type="button"
									>
										{isVisible ? (
											<EyeOff aria-hidden="true" size={16} strokeWidth={2} />
										) : (
											<Eye aria-hidden="true" size={16} strokeWidth={2} />
										)}
									</button>
									<div
										aria-label="Password strength"
										aria-valuemax={4}
										aria-valuemin={0}
										aria-valuenow={strengthScore}
										className="mt-3 mb-4 h-1 w-full overflow-hidden rounded-full bg-border"
										role="progressbar"
									>
										<div
											className={cn(
												"h-full transition-all duration-500 ease-out",
												getStrengthColor(strengthScore),
											)}
											style={{ width: `${(strengthScore / 4) * 100}%` }}
										/>
									</div>
								</div>
							</FormControl>
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="mustChangePassword"
					render={({ field }) => (
						<FormItem className="w-full">
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="mustChangePassword">
									Forza cambio password al prossimo accesso
								</FormLabel>
								<FormControl>
									<Switch
										checked={field.value}
										className="data-[state=checked]:bg-neutral-700"
										id="mustChangePassword"
										onCheckedChange={field.onChange}
									/>
								</FormControl>
								<FormMessage />
							</div>
						</FormItem>
					)}
				/>
				<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>
					)}
				/>

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