"use client";
import { useSession } from "next-auth/react";
import { useDispatchConnectionStore } from "../../../_store/connectionStore";
import { useRef, useState } from "react";

export const ConnectionBtn = () => {
	const modalRef = useRef<HTMLDialogElement>(null);
	const connection = useDispatchConnectionStore((state) => state);
	const [form, setForm] = useState({
		logoffTime: "",
		selectedZone: "LST_01",
	});
	const session = useSession();
	const uid = session.data?.user?.id;
	if (!uid) return null;
	return (
		<>
			{!connection.isConnected ? (
				<button
					className="btn btn-soft btn-info"
					onClick={() => modalRef.current?.showModal()}
				>
					Verbinden
				</button>
			) : (
				<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.isConnected ? (
						<h3 className="text-lg font-bold mb-5">
							Verbunden als{" "}
							<span className="text-info">
								&lt;{connection.selectedZone}&gt;
							</span>
						</h3>
					) : (
						<h3 className="text-lg font-bold mb-5">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) =>
									setForm({
										...form,
										logoffTime: e.target.value,
									})
								}
								value={form.logoffTime}
								type="time"
								className="input w-full"
							/>
						</label>
						{!connection.isConnected && (
							<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.isConnected ? (
								<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.selectedZone, form.logoffTime);
									}}
									className="btn btn-soft btn-info"
								>
									Verbinden
								</button>
							)}
						</form>
					</div>
				</div>
			</dialog>
		</>
	);
};

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