import { Eye, EyeOff } from "lucide-react";
import { useState } from "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 { Button, buttonVariants } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import { Label } from "~/components/ui/label";
import { Separator } from "~/components/ui/separator";
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 type { UsersId } from "~/schemas/public/Users";
import { api } from "~/utils/api";

export const OverridePasswordForm = ({ id }: { id: UsersId }) => {
	const {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		toggleVisibility,
	} = useStrongPassword();

	const OverridePasswordFormSchema = z
		.object({
			password: z.string(),
		})
		.superRefine(({ password }, refinementContext) => {
			passwordRefine({
				password,
				refinementContext,
				path: "password",
			});
		});

	type OverridePasswordFormValues = z.infer<typeof OverridePasswordFormSchema>;

	const { locale, t } = useTranslation();

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

	const form = useZodForm(OverridePasswordFormSchema, {
		defaultValues: {
			password: "",
		},
	});

	const { mutate } = api.auth.OverridePassword.useMutation({
		onSuccess: () => {
			toast.success(t.overridePw.pwAggiornata);
			form.reset();
		},
		onError: (error) => {
			toast.error(error.message);
		},
	});

	async function onSubmit(fields: OverridePasswordFormValues) {
		mutate({
			id: id,
			password: fields.password,
		});
		form.reset();
		await form.trigger("password");
	}
	const [resetToken, setResetToken] = useState("");
	const { mutate: resetToken_mutate } = api.auth.genPswResetToken.useMutation({
		onSuccess: (data) => {
			setResetToken(data);
		},
	});

	return (
		<Form {...form}>
			<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 px-0.5">
				<div className="flex flex-col items-start gap-2">
					<Label htmlFor="resetLink">Genera un Link di Reset Password</Label>
					<Dialog>
						<DialogTrigger asChild>
							<Button variant="info" id="resetLink">
								Pw Reset link
							</Button>
						</DialogTrigger>
						<DialogContent className="max-w-2xl">
							<DialogHeader>
								<DialogTitle>Strumento Reset Password</DialogTitle>
								<DialogDescription className="sr-only">Edit</DialogDescription>
							</DialogHeader>
							<div className="space-y-4 py-4">
								<Button
									className="inline-flex h-10 items-center justify-center rounded-md bg-blue-500 px-4 py-2 text-sm font-medium whitespace-nowrap text-white ring-offset-white transition-colors hover:bg-blue-500/90"
									onClick={() => resetToken_mutate({ id })}
								>
									Genera
								</Button>
								<Separator />
								<h4>Reset Token</h4>
								<Button
									variant="link"
									onClick={async () => {
										await navigator.clipboard.writeText(resetToken);
										toast("Token copiato", { icon: "🔑" });
									}}
								>
									{resetToken}
								</Button>
								<Separator />
								<h4>Link</h4>
								<Button
									variant="link"
									onClick={async () => {
										await navigator.clipboard.writeText(
											`infoalloggi.it/auth/password-reset/${resetToken}`,
										);
										toast("Link copiato", { icon: "🔗" });
									}}
								>
									{`infoalloggi.it/auth/password-reset/${resetToken}`}
								</Button>
							</div>
						</DialogContent>
					</Dialog>
				</div>
				<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
										type="button"
										className={cn(
											buttonVariants({
												variant: "outline",
												size: "sm",
											}),
										)}
										onClick={async () => {
											form.setValue("password", generatePassword());
											await form.trigger("password");
										}}
									>
										genera password
									</button>
								</div>

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

							<FormControl>
								<div className="relative">
									<Input
										{...field}
										id="password"
										className="pe-9"
										placeholder="Password"
										type={isVisible ? "text" : "password"}
										onChange={async (e) => {
											field.onChange(e);
											await form.trigger("password");
										}}
										aria-invalid={form.getFieldState("password").invalid}
										aria-describedby="password-strength"
									/>
									<button
										className="text-muted-foreground/80 hover:text-foreground focus-visible:border-ring focus-visible:text-foreground focus-visible:ring-ring/30 absolute end-0 top-1 flex size-9 items-center justify-center rounded-e-lg transition-shadow focus-visible:border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
										type="button"
										onClick={toggleVisibility}
										aria-label={isVisible ? "Hide password" : "Show password"}
										aria-pressed={isVisible}
										aria-controls="password"
									>
										{isVisible ? (
											<EyeOff size={16} strokeWidth={2} aria-hidden="true" />
										) : (
											<Eye size={16} strokeWidth={2} aria-hidden="true" />
										)}
									</button>
									<div
										className="bg-border mt-3 mb-4 h-1 w-full overflow-hidden rounded-full"
										role="progressbar"
										aria-valuenow={strengthScore}
										aria-valuemin={0}
										aria-valuemax={4}
										aria-label="Password strength"
									>
										<div
											className={cn(
												"h-full transition-all duration-500 ease-out",
												getStrengthColor(strengthScore),
											)}
											style={{ width: `${(strengthScore / 4) * 100}%` }}
										/>
									</div>
								</div>
							</FormControl>
						</FormItem>
					)}
				/>
				<Button type="submit">{t.overridePw.aggiorna}</Button>
			</form>
		</Form>
	);
};
