"use client";
import { PlaneIcon, Workflow } from "lucide-react";
import { useSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";

export const StatsToggle = () => {
	const [checked, setChecked] = useState(false);
	const session = useSession();
	const router = useRouter();
	const searchParams = useSearchParams();

	useEffect(() => {
		const statsPage = searchParams.get("stats") || "pilot";
		if (statsPage === "dispo") {
			setChecked(false);
		} else {
			setChecked(true);
		}
	}, [searchParams]);

	useEffect(() => {
		if (checked) {
			router.push("/?stats=pilot");
		} else {
			router.push("/?stats=dispo");
		}
	}, [checked, router]);

	return (
		<header className="flex justify-between items-center p-4">
			<h1 className="text-2xl font-bold">
				Hallo, {session.status === "authenticated" ? session.data?.user.firstname : "<username>"}
				{"!"}
			</h1>
			<div>
				<div className="tooltip tooltip-left" data-tip="Disponent / Pilot">
					<label className="toggle text-base-content">
						<input
							type="checkbox"
							checked={checked}
							onChange={(e) => setChecked(e.target.checked)}
						/>
						<Workflow className="w-4 h-4" viewBox="0 0 24 24" aria-label="enabled" />
						<PlaneIcon className="w-4 h-4" viewBox="0 0 24 24" aria-label="disabled" />
					</label>
				</div>
			</div>
		</header>
	);
};
