import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { TextLink } from "@/components/ui/text-link";
import LogoWithText from "@/icons/logo-with-text.svg?react";

export const Route = createFileRoute("/magic-link/$magic-link")({
	component: RouteComponent,
});

function RouteComponent() {
	const navigate = useNavigate();
	const { "magic-link": magicLink } = Route.useParams();

	const [code, setCode] = useState<string[]>(Array(6).fill(""));
	const [isAutoSubmitted, setIsAutoSubmitted] = useState(false);

	const [resendTimeout, setResendTimeout] = useState(() => {
		const savedTimeout = localStorage.getItem("resendTimeout");
		const savedTimestamp = localStorage.getItem("resendTimeoutTimestamp");

		if (savedTimeout && savedTimestamp) {
			const secondsPassed = Math.floor(
				(Date.now() - Number(savedTimestamp)) / 1000,
			);
			const remainingTime = Math.max(0, Number(savedTimeout) - secondsPassed);
			return remainingTime > 0 ? Math.floor(remainingTime) : 0;
		}
		return 0;
	});

	useEffect(() => {
		if (magicLink && /^\d{6}$/.test(magicLink)) {
			const codeArray = magicLink.split("").slice(0, 6);
			setCode(codeArray);

			const timer = setTimeout(() => {
				handleConfirm(codeArray.join(""));
			}, 800);

			return () => clearTimeout(timer);
		}
	}, [magicLink]);

	useEffect(() => {
		if (resendTimeout <= 0) {
			localStorage.removeItem("resendTimeout");
			localStorage.removeItem("resendTimeoutTimestamp");
			return;
		}

		localStorage.setItem("resendTimeout", resendTimeout.toString());
		localStorage.setItem("resendTimeoutTimestamp", Date.now().toString());

		const timer = setTimeout(() => {
			setResendTimeout(resendTimeout - 1);
		}, 1000);

		return () => clearTimeout(timer);
	}, [resendTimeout]);

	const handleChange = (index: number, value: string) => {
		if (!/^\d?$/.test(value)) return;

		const newCode = [...code];
		newCode[index] = value;
		setCode(newCode);

		if (value && index < 5) {
			const nextInput = document.getElementById(`code-input-${index + 1}`);
			nextInput?.focus();
		}
	};

	const handleKeyDown = (
		index: number,
		e: React.KeyboardEvent<HTMLInputElement>,
	) => {
		if (e.key === "Backspace") {
			const newCode = [...code];

			if (code[index] === "") {
				if (index > 0) {
					newCode[index - 1] = "";
					setCode(newCode);
					document.getElementById(`code-input-${index - 1}`)?.focus();
				}
			} else {
				newCode[index] = "";
				setCode(newCode);
			}
		}
	};

	const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
		const pasted = e.clipboardData
			.getData("Text")
			.replace(/\D/g, "")
			.slice(0, 6);
		if (!pasted) return;

		const newCode = [...code];
		for (let i = 0; i < pasted.length; i++) {
			newCode[i] = pasted[i];
		}
		setCode(newCode);

		const nextIndex = pasted.length < 6 ? pasted.length : 5;
		document.getElementById(`code-input-${nextIndex}`)?.focus();
	};

	const handleResendClick = () => {
		setResendTimeout(60);
	};

	const handleConfirm = (fullCode: string) => {
		console.log(fullCode);
		navigate({
			to: "/auth/username",
			viewTransition: { types: ["warp"] },
		});
	};

	return (
		<div className="h-full pt-5">
			<Link
				to="/"
				viewTransition={{ types: ["warp"] }}
				className="px-10 h-[52px] flex items-center absolute"
			>
				<LogoWithText />
			</Link>
			<div className="flex items-center justify-center h-full gap-10 tracking-[-2%] flex-col">
				<div className="text-brand-gray text-center">
					<p className="font-medium text-[48px] leading-[120%]">
						Welcome to Cytonic!
					</p>
					<p className="font-medium text-[32px] leading-[120%]">Sign in</p>
				</div>

				<div className="space-y-10">
					<div className="flex space-x-2">
						{code.map((digit, i) => (
							<Input
								key={i}
								id={"code-input-${i}"}
								className="w-10 h-10 p-0 text-center text-lg"
								type="text"
								inputMode="numeric"
								pattern="\d*"
								maxLength={1}
								value={digit}
								onPaste={handlePaste}
								onChange={(e) => handleChange(i, e.target.value)}
								onKeyDown={(e) => handleKeyDown(i, e)}
								autoComplete="one-time-code"
								readOnly={isAutoSubmitted}
							/>
						))}
					</div>

					<div className="space-y-4">
						<Button
							className="text-[18px] w-full"
							disabled={code.some((c) => c === "") || isAutoSubmitted}
							onClick={() => handleConfirm(code.join(""))}
						>
							{isAutoSubmitted ? "Processing..." : "Confirm"}
						</Button>

						<div className="text-[14px] w-[286px] whitespace-nowrap">
							<span className="tracking-[-2%] text-text-light-200">
								Didn't receive a code?
							</span>
							{resendTimeout > 0 ? (
								<span className="font-[500] ml-4">
									Next resend in {resendTimeout}s
								</span>
							) : (
								<TextLink
									className="font-[500] ml-4"
									onClick={handleResendClick}
								>
									[ Click to resend ]
								</TextLink>
							)}
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
