import { observer } from "mobx-react-lite";
import { useRef, useState } from "react";
import Arrow from "@/icons/arrow.svg?react";
import Paperclip from "@/icons/paperclip.svg?react";

import { cn } from "@/lib/utils";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useAccountStore } from "@/contexts/AccountContext";
import { Button } from "../ui/button";

const Chat = observer(() => {
	const { id } = useParams({ from: "/interaction-panel/$id" });
	return (
		<div className="flex-1  h-full flex items-center justify-center">{id}</div>
	);
});

const ChatInput = () => {
	const navigate = useNavigate();
	const { userId } = useAccountStore();

	const [message, setMessage] = useState("");
	const [showShadow, setShowShadow] = useState(false);
	const textareaRef = useRef<HTMLTextAreaElement>(null);

	const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
		const el = e.target;
		setMessage(el.value);

		el.style.height = "auto";
		el.style.height = `${Math.min(el.scrollHeight, 200)}px`;

		setShowShadow(el.scrollTop + el.clientHeight < el.scrollHeight);
	};

	const handleScroll = () => {
		const el = textareaRef.current;
		if (!el) return;
		setShowShadow(el.scrollTop + el.clientHeight < el.scrollHeight);
	};

	return (
		<div
			className="relative border border-[#E8E8E8] rounded-[16px] pt-4 pb-2 pl-4 pr-2 flex flex-col justify-between transition-all duration-200"
			style={{
				boxShadow: "0px 1px 8px 0px #00000012",
			}}
		>
			<div className="relative">
				<textarea
					ref={textareaRef}
					onInput={handleInput}
					onScroll={handleScroll}
					className="text-[14px] placeholder:text-[#818181] focus:outline-none overflow-y-auto min-h-[40px] max-h-[150px] resize-none w-full pr-4"
					placeholder="Ask whatever you want..."
					value={message}
					rows={1}
				/>

				<div
					className={cn(
						"absolute left-0 bottom-0 w-full h-5 pointer-events-none transition-opacity duration-300",
						showShadow ? "opacity-100" : "opacity-0",
					)}
					style={{
						background:
							"linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.95), #ffffff)",
					}}
				/>
			</div>

			<div className="flex justify-between items-center mt-2">
				<div className="flex gap-6">
					<span className="flex gap-2 items-center cursor-pointer">
						<Paperclip />
						<p className="text-[14px] text-[#C0C0C0]">Add attachment</p>
					</span>
				</div>

				<div className="flex items-center gap-4">
					<Button
						className="w-10 h-10 rotate-180"
						disabled={message.trim() === ""}
						onClick={() => {
							if (userId === undefined) {
								navigate({
									to: "/auth/mail",
									viewTransition: { types: ["warp"] },
								});
							}
						}}
					>
						<Arrow color="white" />
					</Button>
				</div>
			</div>
		</div>
	);
};

export { Chat, ChatInput };
