"use client";
import { useSession } from "next-auth/react";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { getStationsAPI } from "_querys/stations";

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 { data: stations } = useQuery({
		queryKey: ["stations"],
		queryFn: () => getStationsAPI(),
	});

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

	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-soft btn-error"
					type="submit"
					onSubmit={() => false}
					onClick={() => {
						connection.disconnect();
					}}
				>
					Trennen
				</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>
					)}
					<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 (UTC+1)</span>
							<input
								onChange={(e) =>
									setForm({
										...form,
										logoffTime: e.target.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">Abbrechen</button>
							{connection.status == "connected" ? (
								<button
									className="btn btn-soft btn-error"
									type="submit"
									onSubmit={() => false}
									onClick={() => {
										connection.disconnect();
									}}
								>
									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>
	);
};
