/* eslint-disable react-hooks/exhaustive-deps */
"use client";
import { useSession } from "next-auth/react";
import { useDispatchConnectionStore } from "../../../../../_store/dispatch/connectionStore";
import { useEffect, useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Prisma } from "@repo/db";
import { changeDispatcherAPI } from "_querys/dispatcher";
import { Button, getNextDateWithTime } from "@repo/shared-components";
import { Ghost } from "lucide-react";

export const ConnectionBtn = () => {
	const modalRef = useRef<HTMLDialogElement>(null);
	const connection = useDispatchConnectionStore((state) => state);
	const [form, setForm] = useState({
		logoffTime: "",
		selectedZone: "LST_01",
		ghostMode: false,
	});
	const changeDispatcherMutation = useMutation({
		mutationFn: ({ id, data }: { id: number; data: Prisma.ConnectedDispatcherUpdateInput }) =>
			changeDispatcherAPI(id, data),
	});
	const session = useSession();
	const uid = session.data?.user?.id;

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

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

			{connection.status == "connected" ? (
				<button
					className="btn btn-sm btn-soft btn-success"
					type="submit"
					onSubmit={() => false}
					onClick={() => {
						modalRef.current?.showModal();
					}}
				>
					Verbunden {connection.ghostMode && <Ghost />}
				</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="mb-5 text-lg font-bold">
							Verbunden als <span className="text-info">&lt;{connection.selectedZone}&gt;</span>
						</h3>
					) : (
						<h3 className="mb-5 text-lg font-bold">Als Disponent anmelden</h3>
					)}
					<fieldset className="fieldset w-full">
						<label className="floating-label w-full text-base">
							<span>Logoff Zeit (UTC+1)</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>
					{session.data?.user.permissions.includes("ADMIN_KICK") &&
						connection.status === "disconnected" && (
							<fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4">
								<legend className="fieldset-legend">Ghost-Mode</legend>
								<label className="label">
									<input
										checked={form.ghostMode}
										onChange={(e) => setForm({ ...form, ghostMode: e.target.checked })}
										type="checkbox"
										className="checkbox"
									/>
									Vesteckt deine Verbindung auf dem Tracker
								</label>
							</fieldset>
						)}
					<div className="modal-action flex w-full justify-between">
						<form method="dialog" className="flex w-full justify-between">
							<button className="btn btn-soft">Zurück</button>
							{connection.status == "connected" ? (
								<>
									<Button
										className="btn"
										onClick={async () => {
											if (!connection.connectedDispatcher?.id) return;
											const [logoffHours, logoffMinutes] =
												form.logoffTime?.split(":").map(Number) || [];
											await changeDispatcherMutation.mutateAsync({
												id: connection.connectedDispatcher?.id,
												data: {
													esimatedLogoutTime:
														logoffHours !== undefined && logoffMinutes !== undefined
															? getNextDateWithTime(logoffHours, logoffMinutes)
															: null,
												},
											});
											modalRef.current?.close();
										}}
									>
										Logoff-Zeit speichern
									</Button>
									<button
										className="btn btn-soft btn-error"
										type="submit"
										onSubmit={() => false}
										onClick={() => {
											connection.disconnect();
										}}
									>
										Verbindung Trennen
									</button>
								</>
							) : (
								<button
									type="submit"
									onSubmit={() => false}
									onClick={() => {
										const [logoffHours, logoffMinutes] =
											form.logoffTime?.split(":").map(Number) || [];
										connection.connect(
											uid,
											form.selectedZone,
											form.logoffTime && logoffHours !== undefined && logoffMinutes !== undefined
												? getNextDateWithTime(logoffHours, logoffMinutes).toISOString()
												: "",
											form.ghostMode,
										);
									}}
									className="btn btn-soft btn-info"
								>
									{connection.status == "disconnected" ||
									// eslint-disable-next-line @typescript-eslint/no-explicit-any
									(connection.status as any) === ""
										? "Verbinden"
										: connection.status}
								</button>
							)}
						</form>
					</div>
				</div>
			</dialog>
		</div>
	);
};

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