"use client";
import { ChatBubbleIcon, PaperPlaneIcon } from "@radix-ui/react-icons";
import { useLeftMenuStore } from "_store/leftMenuStore";
import { useSession } from "next-auth/react";
import { Fragment, useEffect, useState, useRef } from "react";
import { cn } from "@repo/shared-components";
import { asPublicUser } from "@repo/db";
import { useQuery } from "@tanstack/react-query";
import { getConnectedDispatcherAPI } from "_querys/dispatcher";
import { getConnectedAircraftsAPI } from "_querys/aircrafts";
import { useDispatchConnectionStore } from "_store/dispatch/connectionStore";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { Trash } from "lucide-react";

export const Chat = () => {
	const {
		removeChat,
		setReportTabOpen,
		chatOpen,
		setChatOpen,
		sendMessage,
		addChat,
		chats,
		setOwnId,
		selectedChat,
		setSelectedChat,
		setChatNotification,
	} = useLeftMenuStore();
	const [sending, setSending] = useState(false);
	const session = useSession();
	const [addTabValue, setAddTabValue] = useState<string>("default");
	const [message, setMessage] = useState<string>("");
	const dispatcherConnected = useDispatchConnectionStore((state) => state.status === "connected");
	const pilotConnected = usePilotConnectionStore((state) => state.status === "connected");
	const [someChat, setSomeChat] = useState(false);
	const audioRef = useRef<HTMLAudioElement | null>(null);

	const { data: dispatcher } = useQuery({
		queryKey: ["dispatcher"],
		queryFn: () => getConnectedDispatcherAPI(),
		refetchInterval: 10000,
	});
	const { data: aircrafts } = useQuery({
		queryKey: ["aircrafts"],
		queryFn: () => getConnectedAircraftsAPI(),
		refetchInterval: 10000,
		enabled: dispatcherConnected,
	});

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

	const filteredDispatcher = dispatcher?.filter(
		(d) => d.userId !== session.data?.user.id && !chats[d.userId],
	);
	const filteredAircrafts = aircrafts?.filter(
		(a) => a.userId !== session.data?.user.id && !chats[a.userId],
	);

	const btnActive = pilotConnected || dispatcherConnected;

	useEffect(() => {
		if (!filteredDispatcher?.length && !filteredAircrafts?.length) {
			setAddTabValue("default");
		}
	}, [filteredDispatcher, filteredAircrafts]);

	useEffect(() => {
		if (!btnActive) {
			setChatOpen(false);
		}
	}, [btnActive, setChatOpen]);

	useEffect(() => {
		if (Object.values(chats).some((c) => c.notification)) {
			setSomeChat(true);
			if (audioRef.current) {
				audioRef.current.volume = 0.5;
				audioRef.current.play().catch(() => {});
			}
		} else {
			setSomeChat(false);
		}
	}, [chats]);

	return (
		<div className={cn("dropdown dropdown-right dropdown-center", chatOpen && "dropdown-open")}>
			<audio ref={audioRef} src="/sounds/newChat.mp3" preload="auto" />
			<div className="indicator">
				<button
					className={cn(
						"btn btn-soft btn-sm cursor-default",
						btnActive && "btn-primary cursor-pointer",
						someChat && "border-warning animate-pulse",
					)}
					onClick={() => {
						if (!btnActive) return;
						setReportTabOpen(false);
						setChatOpen(!chatOpen);
						if (selectedChat) {
							setChatNotification(selectedChat, false);
						}
					}}
				>
					<ChatBubbleIcon className="h-4 w-4" />
				</button>
			</div>
			{chatOpen && (
				<div
					tabIndex={0}
					className="dropdown-content card bg-base-200 w-150 border-1 border-primary z-[1100] ml-2 max-h-[480px] shadow-md"
				>
					<div className="card-body relative">
						<button
							className="btn btn-xs btn-circle btn-ghost absolute right-2 top-2"
							onClick={() => setChatOpen(false)}
							type="button"
						>
							<span className="text-xl leading-none">&times;</span>
						</button>
						<h2 className="mb-2 inline-flex items-center gap-2 text-lg font-bold">
							<ChatBubbleIcon /> Chat
						</h2>
						<div className="join">
							<select
								className="select select-sm w-full"
								value={addTabValue}
								onChange={(e) => setAddTabValue(e.target.value)}
							>
								{!filteredDispatcher?.length && !filteredAircrafts?.length && (
									<option disabled value="default">
										Keine Chatpartner gefunden
									</option>
								)}
								{(filteredDispatcher?.length || filteredAircrafts?.length) && (
									<option disabled value="default">
										Chatpartner auswählen
									</option>
								)}

								{filteredDispatcher?.map((dispatcher) => (
									<option key={dispatcher.userId} value={dispatcher.userId}>
										{dispatcher.zone} - {asPublicUser(dispatcher.publicUser).fullName}
									</option>
								))}

								{filteredAircrafts?.map((aircraft) => (
									<option key={aircraft.userId} value={aircraft.userId}>
										{aircraft.Station.bosCallsignShort} -{" "}
										{asPublicUser(aircraft.publicUser).fullName}
									</option>
								))}
							</select>
							<button
								className="btn btn-sm btn-soft btn-primary join-item"
								onClick={() => {
									if (addTabValue === "default") return;
									const aircraftUser = aircrafts?.find((a) => a.userId === addTabValue);
									const dispatcherUser = dispatcher?.find((d) => d.userId === addTabValue);
									const user = aircraftUser || dispatcherUser;
									console.log("Adding chat for user:", addTabValue, user);
									if (!user) return;
									const role = "Station" in user ? user.Station.bosCallsignShort : user.zone;
									console.log("Adding chat for user:", addTabValue);
									addChat(addTabValue, `${asPublicUser(user.publicUser).fullName} (${role})`);
									setSelectedChat(addTabValue);
									setAddTabValue("default");
								}}
							>
								<span className="text-xl">+</span>
							</button>
						</div>
						<div className="tabs tabs-lift max-h-full">
							{Object.keys(chats).map((userId) => {
								const chat = chats[userId];
								if (!chat) return null;
								return (
									<Fragment key={userId}>
										<div
											className={cn("indicator tab", selectedChat === userId && "tab-active")}
											onClick={() => {
												if (selectedChat === userId) {
													setSelectedChat(null);
													return;
												}
												setSelectedChat(userId);
											}}
										>
											{chat.name}
											{chat.notification && <span className="indicator-item status status-info" />}
										</div>
										<div className="tab-content bg-base-100 border-base-300 max-h-[250px] overflow-y-auto p-6">
											{/* So macht man kein overflow handeling, weiß ich. Aber es funktioniert... */}
											{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>
						{!selectedChat && (
							<div role="alert" className="alert alert-info alert-outline">
								<span>Wähle einen Nutzer aus und drücke auf + um einen Chat zu starten</span>
							</div>
						)}
						{selectedChat && (
							<div className="join">
								<button
									className="join-item btn btn-error btn-outline"
									onClick={(e) => {
										e.stopPropagation();
										removeChat(selectedChat);
									}}
									type="button"
								>
									<Trash size={16} />
								</button>
								<div className="w-full">
									<label className="input join-item w-full">
										<input
											type="text"
											required
											className="w-full"
											onChange={(e) => {
												setMessage(e.target.value);
											}}
											onKeyDown={(e) => {
												if (e.key === "Enter" && !e.shiftKey) {
													e.preventDefault();
													if (message.length < 1) return;
													if (!selectedChat) return;
													setSending(true);
													sendMessage(selectedChat, message)
														.then(() => {
															setMessage("");
															setSending(false);
														})
														.catch(() => {
															setSending(false);
														});
												}
											}}
											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} // prevent submit event for react hook form
								>
									{sending ? (
										<span className="loading loading-spinner loading-sm"></span>
									) : (
										<PaperPlaneIcon />
									)}
								</button>
							</div>
						)}
					</div>
				</div>
			)}
		</div>
	);
};
