"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { register } from "../action";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useState } from "react";
import { Button } from "../../../_components/ui/Button";
import { sendVerificationLink } from "(app)/admin/user/action";
import toast from "react-hot-toast";

export const Register = () => {
	const schema = z
		.object({
			email: z
				.string()
				.email({ message: "Gebe eine gültige E-Mail-Adresse ein" })
				.refine(
					(value) => {
						// Regex to check for email aliases like + or %
						const emailAliasRegex = /[+%]/;
						return !emailAliasRegex.test(value);
					},
					{
						message: "Email-Aliase (wie + oder %) sind nicht erlaubt",
					},
				),
			firstname: z
				.string()
				.min(2, {
					message: "Gib einen gültigen Vornamen ein",
				})
				.max(30, {
					message: "Gib einen gültigen Vornamen ein",
				})
				.refine((val) => val.length === 0 || /^[A-ZÄÖÜ]/.test(val), {
					message: "Der Vorname muss mit einem Großbuchstaben beginnen",
				}),
			lastname: z
				.string()
				.min(2, {
					message: "Gib einen gültigen Nachnamen ein",
				})
				.max(30, {
					message: "Gib einen gültigen Nachnamen ein",
				})
				.refine((val) => val.length === 0 || val.includes(" ") || /^[A-ZÄÖÜ]/.test(val), {
					message: "Der Nachname muss mit einem Großbuchstaben beginnen",
				}),
			password: z.string().min(12, {
				message: "Das Passwort muss mindestens 12 Zeichen lang sein",
			}),
			passwordConfirm: z.string(),
		})
		.superRefine(({ password, passwordConfirm }, ctx) => {
			if (password !== passwordConfirm) {
				ctx.addIssue({
					code: "custom",
					message: "Die Passwörter stimmen nicht überein",
					path: ["passwordConfirm"],
				});
			}
		});

	type IFormInput = z.infer<typeof schema>;

	const [isLoading, setIsLoading] = useState(false);

	const form = useForm<IFormInput>({
		resolver: zodResolver(schema),
		defaultValues: {
			email: "",
			password: "",
			passwordConfirm: "",
		},
	});
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async () => {
				try {
					setIsLoading(true);
					const values = form.getValues();
					const user = await register({
						email: form.getValues("email").toLowerCase(),
						password: form.getValues("password"),
						firstname: form.getValues("firstname"),
						lastname: form.getValues("lastname"),
					});
					if ("error" in user) {
						toast.error(user.error);
						return;
					}
					await sendVerificationLink(user.id);
					await signIn("credentials", {
						callbackUrl: "/",
						email: user.email,
						password: values.password,
					});
				} catch (error) {
					toast.error(
						error instanceof Error
							? error.message
							: "Es ist ein Fehler aufgetreten. Bitte versuche es später erneut.",
					);
				} finally {
					setIsLoading(false);
				}
			})}
		>
			<h1 className="text-3xl font-bold">Registrierung</h1>
			<span className="text-sm font-medium">
				Zurück zum{" "}
				<Link href="/login" className="link link-accent link-hover">
					Login
				</Link>
			</span>
			<div className="alert alert-info alert-outline justify-center text-center text-sm font-semibold">
				Du warst bereits Nutzer der V1? <br />
				Du musst keinen neuen Account erstellen, sondern kannst dich mit deinen alten Zugangsdaten
				anmelden.
			</div>
			<div className="mb-2 mt-5">
				<label className="input input-bordered mt-2 flex w-full items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						viewBox="0 0 16 16"
						fill="currentColor"
						className="h-4 w-4 opacity-70"
					>
						<path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z" />
					</svg>
					<input
						type="text"
						className="grow"
						{...form.register("firstname")}
						placeholder="Vorname"
					/>
				</label>
				<p className="text-error">
					{typeof form.formState.errors.firstname?.message === "string"
						? form.formState.errors.firstname.message
						: ""}
				</p>
				<label className="input input-bordered mt-2 flex w-full items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						viewBox="0 0 16 16"
						fill="currentColor"
						className="h-4 w-4 opacity-70"
					>
						<path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z" />
					</svg>
					<input
						type="text"
						className="grow"
						{...form.register("lastname")}
						placeholder="Nachname"
					/>
				</label>
				<p className="text-error">
					{typeof form.formState.errors.lastname?.message === "string"
						? form.formState.errors.lastname.message
						: ""}
				</p>
				<div className="divider">Account</div>
				<label className="input input-bordered flex w-full items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						viewBox="0 0 16 16"
						fill="currentColor"
						className="h-4 w-4 opacity-70"
					>
						<path d="M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z" />
						<path d="M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z" />
					</svg>
					<input type="text" className="grow" {...form.register("email")} placeholder="Email" />
				</label>

				<p className="text-error">
					{typeof form.formState.errors.email?.message === "string"
						? form.formState.errors.email.message
						: ""}
				</p>
				<label className="input input-bordered mt-2 flex w-full items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						viewBox="0 0 16 16"
						fill="currentColor"
						className="h-4 w-4 opacity-70"
					>
						<path
							fillRule="evenodd"
							d="M14 6a4 4 0 0 1-4.899 3.899l-1.955 1.955a.5.5 0 0 1-.353.146H5v1.5a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1-.5-.5v-2.293a.5.5 0 0 1 .146-.353l3.955-3.955A4 4 0 1 1 14 6Zm-4-2a.75.75 0 0 0 0 1.5.5.5 0 0 1 .5.5.75.75 0 0 0 1.5 0 2 2 0 0 0-2-2Z"
							clipRule="evenodd"
						/>
					</svg>
					<input
						type="password"
						autoComplete="new-password"
						{...form.register("password")}
						placeholder="Passwort"
						className="grow"
					/>
				</label>
				<p className="text-error">
					{typeof form.formState.errors.password?.message === "string"
						? form.formState.errors.password.message
						: ""}
				</p>
				<label className="input input-bordered mt-2 flex w-full items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						viewBox="0 0 16 16"
						fill="currentColor"
						className="h-4 w-4 opacity-70"
					>
						<path
							fillRule="evenodd"
							d="M14 6a4 4 0 0 1-4.899 3.899l-1.955 1.955a.5.5 0 0 1-.353.146H5v1.5a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1-.5-.5v-2.293a.5.5 0 0 1 .146-.353l3.955-3.955A4 4 0 1 1 14 6Zm-4-2a.75.75 0 0 0 0 1.5.5.5 0 0 1 .5.5.75.75 0 0 0 1.5 0 2 2 0 0 0-2-2Z"
							clipRule="evenodd"
						/>
					</svg>
					<input
						type="password"
						autoComplete="new-password"
						{...form.register("passwordConfirm")}
						placeholder="Passwort bestätigen"
						className="grow"
					/>
				</label>
				<p className="text-error">
					{typeof form.formState.errors.passwordConfirm?.message === "string"
						? form.formState.errors.passwordConfirm.message
						: ""}
				</p>
				<div className="card-actions mt-6">
					<Button disabled={isLoading} isLoading={isLoading} className="btn btn-primary btn-block">
						Registrieren
					</Button>
				</div>
			</div>
		</form>
	);
};
