"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 === "disconnected" && (
				<button
					className="btn btn-sm btn-soft btn-info "
					onClick={() => modalRef.current?.showModal()}
				>
					Verbinden
				</button>
			)}

			{connection.status == "connected" && (
				<button
					className="btn btn-soft btn-success"
					onClick={() => modalRef.current?.showModal()}
				>
					Verbunden
				</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();
									}}
								>
									Verbindung Trennen
								</button>
							) : (
								<button
									type="submit"
									onSubmit={() => false}
									onClick={() => {
										connection.connect(
											uid,
											form.selectedStationId?.toString() || "",
											form.logoffTime || "",
											stations?.find(
												(station) =>
													station.id ===
													parseInt(form.selectedStationId?.toString() || ""),
											)!,
										);
									}}
									className="btn btn-soft btn-info"
								>
									Verbinden
								</button>
							)}
						</form>
					</div>
				</div>
			</dialog>
		</div>
	);
};

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