"use client";
import { useSession } from "next-auth/react";
import { connectionStore } from "../../_store/connectionStore";
import { useEffect } from "react";
import { CheckCircledIcon } from "@radix-ui/react-icons";

export const ConnectBtn = () => {
	return (
		<>
			<button
				className="btn btn-soft btn-info"
				onClick={() =>
					(
						document.getElementById("my_modal_1") as HTMLDialogElement
					)?.showModal()
				}
			>
				Verbinden
			</button>
			<dialog id="my_modal_1" className="modal">
				<div className="modal-box flex flex-col items-center justify-center">
					<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 type="time" className="input w-full" />
						</label>
						<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>
							<button className="btn btn-soft btn-info">Verbinden</button>
						</form>
					</div>
				</div>
			</dialog>
		</>
	);
};

export const ConnectedBtn = () => {
	return (
		<>
			<button
				className="btn btn-soft btn-success"
				onClick={() =>
					(
						document.getElementById("my_modal_1") as HTMLDialogElement
					)?.showModal()
				}
			>
				Verbunden
			</button>
			<dialog id="my_modal_1" className="modal">
				<div className="modal-box flex flex-col items-center justify-center">
					<h3 className="text-lg font-bold mb-5">
						Verbunden als <span className="text-info">&lt;LST_01&gt;</span>
					</h3>
					<fieldset className="fieldset w-full">
						<label className="floating-label w-full text-base join">
							<span>Logoff Zeit (UTC+1)</span>
							<input type="time" className="input w-full" />
							<button className="btn btn-soft btn-info join-item">
								<CheckCircledIcon className="w-4 h-4" /> Save
							</button>
						</label>
					</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>
							<button className="btn btn-soft btn-error">
								Verbindung Trennen
							</button>
						</form>
					</div>
				</div>
			</dialog>
		</>
	);
};

export const Connection = () => {
	const session = useSession();
	const cStore = connectionStore((state) => state);
	const uid = session.data?.user?.id;

	useEffect(() => {
		if (uid) {
			cStore.connect(uid);
		}
	}, [uid]);

	return <div>{cStore.isConnected ? <ConnectedBtn /> : <ConnectBtn />}</div>;
};
