import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { TextLink } from "@/components/ui/text-link";

export const Route = createFileRoute("/auth/code")({
	component: RouteComponent,
});

function RouteComponent() {
	const navigate = useNavigate();
	const [code, setCode] = useState<string[]>(Array(6).fill(""));

	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(() => {
		document.getElementById("code-input-0")?.focus();
	}, []);

	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 handleSubmit = () => {
		const fullCode = code.join("");
		console.log("Confirm code:", fullCode);
		navigate({
			to: "/auth/username",
			viewTransition: { types: ["warp"] },
		});
	};

	return (
		<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>
				<p className="text-text-light-200 whitespace-nowrap mt-4">
					We’ve sent a code to{" "}
					<span className="text-text-light-900">email@example.com </span>
				</p>
			</div>

			<form
				onSubmit={(e) => {
					e.preventDefault();
					if (code.every((c) => c !== "")) {
						handleSubmit();
					}
				}}
				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"
						/>
					))}
				</div>

				<div className="space-y-4">
					<Button
						type="submit"
						className="text-[18px] w-full"
						disabled={code.some((c) => c === "")}
					>
						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>
			</form>
		</div>
	);
}
