"use client";

import { SendHorizontal, SmilePlusIcon, ThumbsUp } from "lucide-react";
import {
	type ChangeEvent,
	useCallback,
	useEffect,
	useRef,
	useState,
} from "react";
import { ChatAttachments } from "~/components/chat/chat-attachments";
import {
	type AutosizeTextAreaRef,
	AutosizeTextarea,
} from "~/components/custom_ui/autoResizeTextArea";
import {
	EmojiPicker,
	EmojiPickerContent,
	EmojiPickerSearch,
} from "~/components/custom_ui/emoji-picker";
import { Button } from "~/components/ui/button";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "~/components/ui/popover";
import { useThrottledIsTypingMutation } from "~/hooks/chatHooks";
import { useMediaQuery } from "~/hooks/use-media-query";
import { useTranslation } from "~/providers/I18nProvider";
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { Session } from "~/server/api/trpc";
import type { ChatUserInfo } from "~/server/services/chat.service";
import { api } from "~/utils/api";

type ChatBottombarProps = {
	chatId: ChatsChatid;
	userData: Session;
	chatUserData: ChatUserInfo;
};

export default function ChatBottombar({
	chatId,
	userData,
	chatUserData,
}: ChatBottombarProps) {
	const { locale } = useTranslation();
	const [message, setMessage] = useState("");
	const [isFocused, setIsFocused] = useState(false);
	const inputRef = useRef<AutosizeTextAreaRef>(null);

	const { mutate: addMutation } = api.messagesSSE.add.useMutation({});

	const handleThumbsUp = useCallback(() => {
		addMutation({
			chatId,
			message: "👍",
			sender: userData.id,
		});
		setMessage("");
	}, [chatId, addMutation, userData]);

	const handleSend = () => {
		if (message.length !== 0) {
			addMutation({
				chatId,
				message: message.trim(),
				sender: userData.id,
			});

			setMessage("");

			if (inputRef.current) {
				inputRef.current.textArea.focus();
				inputRef.current.textArea.style.height = "auto";
			}
		}
	};
	const isTypingMutation = useThrottledIsTypingMutation({
		chatId,
		username: userData.username,
	});

	useEffect(() => {
		// update isTyping state
		isTypingMutation(isFocused && message.trim().length > 0);
	}, [isFocused, message, isTypingMutation]);

	useEffect(() => {
		if (inputRef.current) {
			inputRef.current.textArea.focus();
		}
	}, []);
	const [openEmoji, setOpenEmoji] = useState(false);

	const isMobile = useMediaQuery("(min-width: 426px)");
	return (
		<div className="flex min-h-18.5 w-full items-center justify-between gap-2 p-2">
			<div className="flex">
				<ChatAttachments chatUserData={chatUserData} userData={userData} />
			</div>
			<div className="relative w-full">
				<AutosizeTextarea
					autoComplete="off"
					className="flex h-14 min-h-14 w-full resize-none items-center overflow-hidden rounded-xl border bg-background pr-8 outline-hidden ring-0 hover:border-neutral-400 focus:border-neutral-600 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"
					minHeight={56}
					name="message"
					onBlur={() => setIsFocused(false)}
					onChange={(e: ChangeEvent<HTMLTextAreaElement>) => {
						setMessage(e.target.value);
					}}
					onFocus={() => setIsFocused(true)}
					onKeyDown={(e) => {
						if (e.key === "Enter") {
							e.preventDefault();
							if (e.shiftKey) {
								setMessage((prev) => `${prev}\n`);
							} else {
								handleSend();
							}
						}
					}}
					placeholder="Aa"
					ref={inputRef}
					value={message}
				/>
				{isMobile && (
					<div className="absolute top-0 right-2 flex h-full items-center">
						<Popover onOpenChange={setOpenEmoji} open={openEmoji}>
							<PopoverTrigger asChild>
								<Button variant="ghost">
									<SmilePlusIcon className="stroke-muted-foreground" />
								</Button>
							</PopoverTrigger>
							<PopoverContent align="end" className="w-fit p-0">
								<EmojiPicker
									className="h-84"
									locale={locale as "it" | "en"}
									onEmojiSelect={({ emoji }) => {
										setMessage(message + emoji);
										// if (inputRef.current) {
										//   inputRef.current.textArea.focus();
										// }
									}}
								>
									<EmojiPickerSearch
										placeholder={locale === "en" ? "Search..." : "Cerca..."}
									/>
									<EmojiPickerContent />
								</EmojiPicker>
							</PopoverContent>
						</Popover>
					</div>
				)}
			</div>
			<Button
				aria-label="Send Message"
				className="shrink-0"
				onClick={
					message.length !== 0 ? () => handleSend() : () => handleThumbsUp()
				}
				variant="ghost"
			>
				{message.length !== 0 ? (
					<SendHorizontal className="text-muted-foreground" size={20} />
				) : (
					<ThumbsUp className="text-muted-foreground" size={20} />
				)}
			</Button>
		</div>
	);
}
