"use client";
import { useSession } from "next-auth/react";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getStationsAPI } from "_querys/stations";
import toast from "react-hot-toast";
import { editConnectedAircraftAPI } from "_querys/aircrafts";
import { Prisma } from "@repo/db";

export const ConnectionBtn = () => {
	const modalRef = useRef<HTMLDialogElement>(null);
	const connection = usePilotConnectionStore((state) => state);
	const [form, setForm] = useState<{
		logoffTime: string | null;
		selectedStationId: number | null;
	}>({
		logoffTime: null,
		selectedStationId: null,
	});
	const [logoffDebounce, setLogoffDebounce] = useState<NodeJS.Timeout | null>(null);

	const { data: stations } = useQuery({
		queryKey: ["stations"],
		queryFn: () => getStationsAPI(),
	});
	const aircraftMutation = useMutation({
		mutationFn: ({
			change,
			sessionId,
		}: {
			sessionId: number;
			change: Prisma.ConnectedAircraftUpdateInput;
		}) => editConnectedAircraftAPI(sessionId, change),
	});

	useEffect(() => {
		if (stations && stations.length > 0 && form.selectedStationId === null) {
			setForm((prevForm) => ({
				...prevForm,
				selectedStationId: stations[0]?.id ?? null,
			}));
		}
	}, [stations, form.selectedStationId]);

	useEffect(() => {
		// Disconnect the socket when the component unmounts
		return () => {
			connection.disconnect();
		};
	}, [connection.disconnect]);

	const logoffTime = form.logoffTime;

	useEffect(() => {
		if (!logoffTime || !connection.connectedAircraft) return;

		if (logoffDebounce) clearTimeout(logoffDebounce);

		const timeout = setTimeout(async () => {
			if (!connection.connectedAircraft?.id) return;
			await aircraftMutation.mutateAsync({
				sessionId: connection.connectedAircraft.id,
				change: {
					esimatedLogoutTime: logoffTime
						? new Date(new Date().toDateString() + " " + logoffTime).toISOString()
						: null,
				},
			});
			modalRef.current?.close();
			toast.success("Änderung gespeichert!");
		}, 2000);

		setLogoffDebounce(timeout);

		// Cleanup function to clear timeout
		return () => {
			if (logoffDebounce) clearTimeout(logoffDebounce);
		};
	}, [logoffTime, connection.connectedAircraft]);

	const session = useSession();
	const uid = session.data?.user?.id;
	if (!uid) return null;
	return (
		<div className="rounded-box bg-base-200 flex justify-center items-center gap-2 p-1">
			{connection.message.length > 0 && (
				<span className="mx-2 text-error">{connection.message}</span>
			)}

			{connection.status == "connected" ? (
				<button
					className="btn btn-sm btn-soft btn-success"
					type="submit"
					onSubmit={() => false}
					onClick={() => {
						modalRef.current?.showModal();
					}}
				>
					Verbunden
				</button>
			) : (
				<button
					type="submit"
					onSubmit={() => false}
					onClick={() => {
						modalRef.current?.showModal();
					}}
					className="btn btn-sm btn-soft btn-info"
				>
					{connection.status == "disconnected" ? "Verbinden" : connection.status}
				</button>
			)}

			<dialog ref={modalRef} className="modal">
				<div className="modal-box flex flex-col items-center justify-center">
					{connection.status == "connected" ? (
						<h3 className="text-lg font-bold mb-5">
							Verbunden als{" "}
							<span className="text-info">&lt;{connection.selectedStation?.bosCallsign}&gt;</span>
						</h3>
					) : (
						<h3 className="text-lg font-bold mb-5">Als Pilot anmelden</h3>
					)}
					{connection.status !== "connected" && (
						<fieldset className="fieldset w-full">
							<label className="floating-label w-full text-base">
								<span>Station</span>
								<select
									onChange={(e) =>
										setForm({
											...form,
											selectedStationId: parseInt(e.target.value),
										})
									}
									value={form.selectedStationId ?? ""}
									className="input w-full"
								>
									{stations?.map((station) => (
										<option key={station.id} value={station.id}>
											{station.bosCallsign}
										</option>
									))}
								</select>
							</label>
						</fieldset>
					)}
					<fieldset className="fieldset w-full mt-2">
						<label className="floating-label w-full text-base">
							<span>Logoff Zeit (LCL)</span>
							<input
								onChange={(e) => {
									const value = e.target.value;
									setForm({
										...form,
										logoffTime: value,
									});
								}}
								value={form.logoffTime ?? ""}
								type="time"
								className="input w-full"
							/>
						</label>
						{connection.status == "disconnected" && (
							<p className="fieldset-label">Du kannst diese Zeit später noch anpassen.</p>
						)}
					</fieldset>
					<div className="modal-action flex justify-between w-full">
						<form method="dialog" className="w-full flex justify-between">
							<button className="btn btn-soft">Zurück</button>
							{connection.status == "connected" ? (
								<button
									className="btn btn-soft btn-error"
									type="submit"
									onSubmit={() => false}
									onClick={() => {
										connection.disconnect();
									}}
								>
									Verbindung Trennen
								</button>
							) : (
								<button
									type="submit"
									onSubmit={() => false}
									onClick={() => {
										const selectedStation = stations?.find(
											(station) =>
												station.id === parseInt(form.selectedStationId?.toString() || ""),
										);
										if (selectedStation) {
											connection.connect(
												uid,
												form.selectedStationId?.toString() || "",
												form.logoffTime || "",
												selectedStation,
												session.data!.user,
											);
										}
									}}
									className="btn btn-soft btn-info"
								>
									{connection.status == "disconnected" ? "Verbinden" : connection.status}
								</button>
							)}
						</form>
					</div>
				</div>
			</dialog>
		</div>
	);
};

export const Connection = () => {
	return (
		<div>
			<ConnectionBtn />
		</div>
	);
};
