"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { DiscordAccount, User } from "@repo/db";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { unlinkDiscord, updateUser, changePassword } from "../actions";
import { useRouter } from "next/navigation";
import { Button } from "../../../_components/ui/Button";
import {
	PersonIcon,
	EnvelopeClosedIcon,
	BookmarkIcon,
	DiscordLogoIcon,
	PaperPlaneIcon,
	Link2Icon,
	MixerHorizontalIcon,
	LockClosedIcon,
	LockOpen2Icon,
	LockOpen1Icon,
} from "@radix-ui/react-icons";
import toast from "react-hot-toast";
import { UserOptionalDefaults, UserOptionalDefaultsSchema } from "@repo/db/zod";
import { Bell, Plane } from "lucide-react";
import Link from "next/link";

export const ProfileForm = ({ user }: { user: User }): React.JSX.Element => {
	const schema = z.object({
		firstname: z.string().min(2).max(30),
		lastname: z.string().min(2).max(30),
		email: z.string().email({
			message: "Bitte gebe eine gültige E-Mail Adresse ein",
		}),
		settingsHideLastname: z.boolean(),
		emailVerified: z.boolean(),
	});
	const [isLoading, setIsLoading] = useState(false);
	type IFormInput = z.infer<typeof schema>;

	const form = useForm<IFormInput>({
		defaultValues: {
			firstname: user.firstname,
			lastname: user.lastname,
			email: user.email,
			settingsHideLastname: user.settingsHideLastname,
		},
		resolver: zodResolver(schema),
	});
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async (values) => {
				setIsLoading(true);
				await updateUser(values);
				form.reset(values);
				setIsLoading(false);
				toast.success("Deine Änderungen wurden gespeichert!", {
					style: {
						background: "var(--color-base-100)",
						color: "var(--color-base-content)",
					},
				});
			})}
		>
			<h2 className="card-title">
				<MixerHorizontalIcon className="w-5 h-5" /> Persönliche Informationen
			</h2>
			<div className="text-left">
				<label className="floating-label w-full mb-5 mt-5">
					<span className="text-lg flex items-center gap-2">
						<PersonIcon /> Vorname
					</span>
					<input
						{...form.register("firstname")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={user.firstname}
						placeholder="Vorname"
					/>
				</label>
				{form.formState.errors.firstname && (
					<p className="text-error">{form.formState.errors.firstname.message}</p>
				)}
				<label className="floating-label w-full mb-5">
					<span className="text-lg flex items-center gap-2">
						<PersonIcon /> Nachname
					</span>
					<input
						{...form.register("lastname")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={user.lastname}
						placeholder="Nachname"
					/>
				</label>
				{form.formState.errors.lastname && (
					<p className="text-error">{form.formState.errors.lastname?.message}</p>
				)}
				<label className="label">
					<input type="checkbox" {...form.register("settingsHideLastname")} className="checkbox" />
					Initialien des Nachnamens verstecken
				</label>
				<label className="floating-label w-full mt-4">
					<span className="text-lg flex items-center gap-2">
						<EnvelopeClosedIcon /> E-Mail
					</span>
					<input
						{...form.register("email")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={user.email}
						onChange={(e) => {
							form.setValue("email", e.target.value.trim());
							form.setValue("emailVerified", false);
						}}
						placeholder="E-Mail"
					/>
				</label>
				{form.formState.errors.email && (
					<p className="text-error">{form.formState.errors.email?.message}</p>
				)}
				<div className="card-actions justify-center pt-6">
					<Button
						role="submit"
						className="btn-sm btn-wide btn-outline btn-primary"
						disabled={!form.formState.isDirty}
						isLoading={isLoading}
					>
						<BookmarkIcon /> Speichern
					</Button>
				</div>
			</div>
		</form>
	);
};

export const SocialForm = ({
	discordAccount,
	user,
}: {
	discordAccount?: DiscordAccount;
	user: User;
}): React.JSX.Element | null => {
	const [isLoading, setIsLoading] = useState(false);
	const [vatsimLoading, setVatsimLoading] = useState(false);
	const router = useRouter();

	const schema = z.object({
		vatsimCid: z.number().min(1000).max(9999999),
	});

	type IFormInput = z.infer<typeof schema>;

	const form = useForm<IFormInput>({
		defaultValues: {
			vatsimCid: user?.vatsimCid || undefined,
		},
		resolver: zodResolver(schema),
	});

	if (!user) return null;
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async (values) => {
				form.handleSubmit(async () => {
					setVatsimLoading(true);
				});
				await updateUser({
					vatsimCid: values.vatsimCid,
				});
				setVatsimLoading(false);
				form.reset(values);
				toast.success("Deine Änderungen wurden gespeichert!", {
					style: {
						background: "var(--color-base-100)",
						color: "var(--color-base-content)",
					},
				});
			})}
		>
			<h2 className="card-title mb-5">
				<Link2Icon className="w-5 h-5" /> Verbindungen & Benachrichtigungen
			</h2>
			<div>
				<div>
					{discordAccount ? (
						<Button
							className="btn-success btn-block btn-outline group transition-all duration-0 hover:btn-error"
							isLoading={isLoading}
							onClick={async () => {
								setIsLoading(true);
								await unlinkDiscord(user.id);
								router.refresh();
								setIsLoading(false);
							}}
						>
							<DiscordLogoIcon className="w-5 h-5" />
							<span className="group-hover:hidden">Verbunden mit {discordAccount.username}</span>
							<span className="hidden group-hover:inline">
								Verbindung trennen{isLoading && "..."}
							</span>
						</Button>
					) : (
						<a href={process.env.NEXT_PUBLIC_DISCORD_URL}>
							<button type="button" className="btn btn-primary btn-block" onSubmit={() => false}>
								<DiscordLogoIcon className="w-5 h-5" /> Mit Discord verbinden
							</button>
						</a>
					)}
				</div>
			</div>
			<div className="content-center">
				<label className="floating-label w-full mt-5">
					<span className="text-lg flex items-center gap-2">
						<PaperPlaneIcon /> VATSIM-CID
					</span>
					<input
						type="number"
						className="input input-bordered w-full"
						placeholder="1445241"
						defaultValue={user.vatsimCid as number | undefined}
						{...form.register("vatsimCid", {
							valueAsNumber: true,
						})}
					/>
				</label>
				{form.formState.errors.vatsimCid && (
					<p className="text-error">{form.formState.errors.vatsimCid.message}</p>
				)}
			</div>
			<div className="card-actions justify-center pt-6 mt-auto">
				<Button
					className="btn-sm btn-wide btn-outline btn-primary"
					isLoading={vatsimLoading}
					disabled={!form.formState.isDirty}
					role="submit"
				>
					<BookmarkIcon /> Speichern
				</Button>
			</div>
		</form>
	);
};

export const PasswordForm = (): React.JSX.Element => {
	const schema = z.object({
		password: z.string().min(2).max(30),
		newPassword: z.string().min(2).max(30),
		newPasswordConfirm: z.string().min(2).max(30),
	});
	const [isLoading, setIsLoading] = useState(false);
	type IFormInput = z.infer<typeof schema>;

	const form = useForm<IFormInput>({
		defaultValues: {},
		resolver: zodResolver(schema),
	});
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async (values) => {
				setIsLoading(true);
				const result = await changePassword(values.password, values.newPassword);
				form.reset(values);
				setIsLoading(false);
				if (result.error) {
					form.setError("password", {
						type: "manual",
						message: result.error,
					});
				} else if (result.success) {
					toast.success("Dein Passwort wurde geändert!", {
						style: {
							background: "var(--color-base-100)",
							color: "var(--color-base-content)",
						},
					});
				}
			})}
		>
			<h2 className="card-title">
				<LockClosedIcon className="w-5 h-5" /> Password Ändern
			</h2>
			<div className="">
				<label className="floating-label w-full mt-5 mb-5">
					<span className="text-lg flex items-center gap-2">
						<LockOpen2Icon /> Aktuelles Passwort
					</span>
					<input
						{...form.register("password")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={""}
					/>
				</label>
				{form.formState.errors.password && (
					<p className="text-error">{form.formState.errors.password.message}</p>
				)}
				<label className="floating-label w-full mb-5">
					<span className="text-lg flex items-center gap-2">
						<LockOpen1Icon /> Neues Passwort
					</span>
					<input
						{...form.register("newPassword")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={""}
					/>
				</label>
				{form.formState.errors.newPassword && (
					<p className="text-error">{form.formState.errors.newPassword?.message}</p>
				)}
				<label className="floating-label w-full">
					<span className="text-lg flex items-center gap-2">
						<LockOpen1Icon /> Passwort wiederholen
					</span>
					<input
						{...form.register("newPasswordConfirm")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={""}
					/>
				</label>
				{form.formState.errors.newPasswordConfirm && (
					<p className="text-error">{form.formState.errors.newPasswordConfirm?.message}</p>
				)}
				<div className="card-actions justify-center pt-6">
					<Button
						role="submit"
						className="btn-sm btn-wide btn-outline btn-primary"
						disabled={!form.formState.isDirty}
						isLoading={isLoading}
					>
						<BookmarkIcon /> Speichern
					</Button>
				</div>
			</div>
		</form>
	);
};

export const PilotForm = ({ user }: { user: User }): React.JSX.Element | null => {
	const [isLoading, setIsLoading] = useState(false);

	const form = useForm<UserOptionalDefaults>({
		defaultValues: {
			...user,
			emailVerified: user.emailVerified ?? undefined,
		},
		resolver: zodResolver(UserOptionalDefaultsSchema),
	});

	if (!user) return null;
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async (values) => {
				form.handleSubmit(async () => {
					setIsLoading(true);
				});
				await updateUser(values);
				setIsLoading(false);
				form.reset(values);
				toast.success("Deine Änderungen wurden gespeichert!", {
					style: {
						background: "var(--color-base-100)",
						color: "var(--color-base-content)",
					},
				});
			})}
		>
			<h2 className="card-title mb-5">
				<Plane className="w-5 h-5" /> Pilot
			</h2>
			<div className="content-center">
				<label className="floating-label w-full">
					<span className="text-lg flex items-center gap-2">
						<Bell /> NTFY room
					</span>
					<input
						placeholder="Erhalte eine Benachrichtigung auf dein Handy über NTFY"
						className="input input-bordered w-full"
						{...form.register("settingsNtfyRoom")}
					/>
				</label>

				<p className="label mt-2 w-full">
					<Link
						href="https://docs.virtualairrescue.com/docs/Leitstelle/App-Alarmierung#download"
						target="_blank"
						rel="noopener noreferrer"
						className="link link-hover link-primary"
					>
						Hier
					</Link>
					findest du mehr Informationen!
				</p>

				{form.formState.errors.settingsNtfyRoom && (
					<p className="text-error">{form.formState.errors.settingsNtfyRoom.message}</p>
				)}
			</div>
			<div className="card-actions justify-center pt-6 mt-auto">
				<Button
					className="btn-sm btn-wide btn-outline btn-primary"
					isLoading={isLoading}
					disabled={!form.formState.isDirty}
					role="submit"
				>
					<BookmarkIcon /> Speichern
				</Button>
			</div>
		</form>
	);
};
