"use client";
import { ChatBubbleIcon, PaperPlaneIcon } from "@radix-ui/react-icons";
import { useLeftMenuStore } from "_store/leftMenuStore";
import { useSession } from "next-auth/react";
import { Fragment, useEffect, useRef, useState } from "react";
import { cn } from "helpers/cn";
import { getConenctedUsers } from "helpers/axios";
import {
	asPublicUser,
	ConnectedAircraft,
	ConnectedDispatcher,
	PublicUser,
} from "@repo/db";

export const Chat = () => {
	const {
		chatOpen,
		setChatOpen,
		sendMessage,
		addChat,
		chats,
		setOwnId,
		selectedChat,
		setSelectedChat,
		setChatNotification,
	} = useLeftMenuStore();
	const [sending, setSending] = useState(false);
	const session = useSession();
	const [addTabValue, setAddTabValue] = useState<string>("");
	const [message, setMessage] = useState<string>("");
	const [connectedUser, setConnectedUser] = useState<
		(ConnectedAircraft | ConnectedDispatcher)[] | null
	>(null);
	const timeout = useRef<NodeJS.Timeout | null>(null);

	useEffect(() => {
		if (!session.data?.user.id) return;
		setOwnId(session.data.user.id);
	}, [session, setOwnId]);

	useEffect(() => {
		const fetchConnectedUser = async () => {
			const data = await getConenctedUsers();
			if (data) {
				const filteredConnectedUser = data.filter((user) => {
					return (
						user.userId !== session.data?.user.id &&
						!Object.keys(chats).includes(user.userId)
					);
				});
				setConnectedUser(filteredConnectedUser);
			}
			if (!addTabValue && data[0]) setAddTabValue(data[0].userId);
		};

		timeout.current = setInterval(() => {
			fetchConnectedUser();
		}, 1000000);
		fetchConnectedUser();

		return () => {
			if (timeout.current) {
				clearInterval(timeout.current);
				timeout.current = null;
				console.log("cleared");
			}
		};
	}, [addTabValue, chats, session]);

	return (
		<div
			className={cn("dropdown dropdown-center", chatOpen && "dropdown-open")}
		>
			<div className="indicator">
				{Object.values(chats).some((c) => c.notification) && (
					<span className="indicator-item status status-info"></span>
				)}
				<button
					className="btn btn-soft btn-sm btn-primary"
					onClick={() => {
						console.log("clicked");
						setChatOpen(!chatOpen);
						if (selectedChat) {
							setChatNotification(selectedChat, false);
						}
					}}
				>
					<ChatBubbleIcon className="w-4 h-4" />
				</button>
			</div>
			{chatOpen && (
				<div
					tabIndex={0}
					className="dropdown-content card bg-base-200 w-150 shadow-md z-[1100]"
				>
					<div className="card-body">
						<div className="join">
							<select
								className="select select-sm w-full"
								value={addTabValue}
								onChange={(e) => setAddTabValue(e.target.value)}
							>
								{!connectedUser?.length && (
									<option disabled={true}>Keine Chatpartner gefunden</option>
								)}
								{connectedUser?.map((user) => (
									<option key={user.userId} value={user.userId}>
										{(user.publicUser as unknown as PublicUser).firstname}{" "}
										{(user.publicUser as unknown as PublicUser).lastname}
									</option>
								))}
							</select>
							<button
								className="btn btn-sm btn-soft btn-primary join-item"
								onClick={() => {
									const user = connectedUser?.find(
										(user) => user.userId === addTabValue,
									);
									if (!user) return;
									addChat(addTabValue, asPublicUser(user.publicUser).fullName);
									setSelectedChat(addTabValue);
								}}
							>
								<span className="text-xl">+</span>
							</button>
						</div>
						<div className="tabs tabs-lift">
							{Object.keys(chats).map((userId) => {
								const chat = chats[userId];
								if (!chat) return null;
								return (
									<Fragment key={userId}>
										<input
											type="radio"
											name="my_tabs_3"
											className="tab"
											aria-label={`<${chat.name}>`}
											checked={selectedChat === userId}
											onClick={() => {
												setChatNotification(userId, false);
											}}
											onChange={(e) => {
												if (e.target.checked) {
													// Handle tab change
													setSelectedChat(userId);
												}
											}}
										/>
										<div className="tab-content bg-base-100 border-base-300 p-6">
											{chat.messages.map((chatMessage) => {
												const isSender =
													chatMessage.senderId === session.data?.user.id;
												return (
													<div
														key={chatMessage.id}
														className={`chat ${isSender ? "chat-end" : "chat-start"}`}
													>
														<p className="chat-footer opacity-50">
															{new Date(
																chatMessage.timestamp,
															).toLocaleTimeString()}
														</p>
														<div className="chat-bubble">
															{chatMessage.text}
														</div>
													</div>
												);
											})}
											{!chat.messages.length && (
												<p className="text-xs opacity-50">
													Noch keine Nachrichten
												</p>
											)}
										</div>
									</Fragment>
								);
							})}
						</div>
						<div className="join">
							<div className="w-full">
								<label className="input join-item w-full">
									<input
										type="text"
										required
										className="w-full"
										onChange={(e) => {
											setMessage(e.target.value);
										}}
										value={message}
									/>
								</label>
							</div>
							<button
								className="btn btn-soft join-item"
								onClick={(e) => {
									e.preventDefault();
									if (message.length < 1) return;
									if (!selectedChat) return;
									setSending(true);
									sendMessage(selectedChat, message)
										.then(() => {
											setMessage("");
											setSending(false);
										})
										.catch(() => {
											setSending(false);
										});
									return false;
								}}
								disabled={sending}
								role="button"
								onSubmit={() => false}
							>
								{sending ? (
									<span className="loading loading-spinner loading-sm"></span>
								) : (
									<PaperPlaneIcon />
								)}
							</button>
						</div>
					</div>
				</div>
			)}
		</div>
	);
};
