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 { Button } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import Input from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { Separator } from "~/components/ui/separator";
import { usePassword } from "~/hooks/usePassword";
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,
		maxStrength,
	} = usePassword();

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

	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.PasswordOverride.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: () => {
			toast.success(t.overridePw.pwAggiornata);
			form.reset();
		},
	});

	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 className="space-y-8 px-0.5" onSubmit={form.handleSubmit(onSubmit)}>
				<div className="flex flex-col items-start gap-2">
					<Label htmlFor="resetLink">Genera un Link di Reset Password</Label>
					<Dialog>
						<DialogTrigger asChild>
							<Button id="resetLink" variant="info">
								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 whitespace-nowrap rounded-md bg-blue-500 px-4 py-2 font-medium text-sm text-white ring-offset-white transition-colors hover:bg-blue-500/90"
									onClick={() => resetToken_mutate({ id })}
								>
									Genera
								</Button>
								<Separator />
								<h4>Reset Token</h4>
								<Button
									onClick={async () => {
										await navigator.clipboard.writeText(resetToken);
										toast("Token copiato", { icon: "🔑" });
									}}
									variant="link"
								>
									{resetToken}
								</Button>
								<Separator />
								<h4>Link</h4>
								<Button
									onClick={async () => {
										await navigator.clipboard.writeText(
											`infoalloggi.it/auth/password-reset/${resetToken}`,
										);
										toast("Link copiato", { icon: "🔗" });
									}}
									variant="link"
								>
									{`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
										className="bg-card"
										onClick={async () => {
											form.setValue("password", generatePassword());
											await form.trigger("password");
										}}
										size="sm"
										type="button"
										variant="outline"
									>
										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 cursor-pointer 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={maxStrength}
										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 / maxStrength) * 100}%`,
											}}
										/>
									</div>
								</div>
							</FormControl>
						</FormItem>
					)}
				/>
				<Button type="submit">{t.overridePw.aggiorna}</Button>
			</form>
		</Form>
	);
};
