import { useRef, useEffect, useState } from "react";
import SendIcon from "../icons/SendIcon";
import Button from "../ui/Button";
import clsx from "clsx";
import PopupWrapper from "../PopupWrapper";
import DraggableContainer from "../DraggableContainer";
import { useWebRTC } from "../../hooks/useWebRTC";
import { useChatHistory } from "../../hooks/useChatHistory";
import { useParams } from "react-router";
import { useMe } from "../../hooks/useAuth";

interface ChatPopupProps {
  sessionId?: string;
}

export default function ChatPopup({ sessionId: sessionIdProp }: ChatPopupProps = {}) {
  const headerRef = useRef<HTMLDivElement>(null);
  // Получаем sessionId из пропсов или из URL параметров
  const { id: sessionIdFromParams } = useParams<{ id: string }>();
  const sessionId = sessionIdProp || sessionIdFromParams;
  const {
    chatMessages: realtimeMessages,
    sendMessage,
    currentUserId,
    updateUserId,
  } = useWebRTC();

  // Получаем данные текущего пользователя
  // React Query кэширует результат, поэтому множественные вызовы useMe() не приводят к множественным запросам
  const { data: user } = useMe();

  // Обновляем userId в WebRTC сервисе при авторизации
  useEffect(() => {
    if (user?.id && updateUserId) {
      console.log("[ChatPopup] User authenticated, updating WebRTC userId to:", user.id);
      updateUserId(user.id);
    }
  }, [user?.id, updateUserId]);

  // Определяем идентификатор для сравнения с senderId в сообщениях
  // Приоритет: реальный userId (если авторизован), затем currentUserId (guestId)
  const myIdentifier = user?.id || currentUserId;

  console.log("[ChatPopup] Rendering with sessionId:", sessionId);
  console.log("[ChatPopup] My identifier:", myIdentifier, "isAuthenticated:", !!user, "user.id:", user?.id, "currentUserId:", currentUserId);

  // Загружаем историю через REST API
  const { data: historyMessages = [], isLoading, error } = useChatHistory(sessionId);

  console.log("[ChatPopup] Chat history state:", {
    historyMessages: historyMessages.length,
    isLoading,
    error,
    realtimeMessages: realtimeMessages.length,
  });

  // Объединяем историю и realtime сообщения
  const historyIds = new Set(historyMessages.map((m) => m.id));
  const newRealtimeMessages = realtimeMessages.filter(
    (m) => !historyIds.has(m.id)
  );
  const allMessages = [...historyMessages, ...newRealtimeMessages];

  console.log("[ChatPopup] All messages count:", allMessages.length);

  function onMessageSend(message: string) {
    // Передаем имя пользователя и флаг авторизации
    sendMessage(message, user?.fullName, !!user);
  }

  return (
    <DraggableContainer
      enabled={window.innerWidth >= 640}
      centerVertical
      constrainToBounds
      initialPosition={{ right: "5vw" }}
      dragHandleRef={headerRef}
    >
      <PopupWrapper
        title="Чат"
        className="sm:overflow-hidden"
        headerRef={headerRef}
      >
        <div className="flex flex-col 2xl:h-[19.444vw] max-sm:h-[87.5dvh] 2xl:-m-[1.389vw] -m-5">
          <MessageFeed
            messages={allMessages}
            currentUserId={myIdentifier}
            isLoading={isLoading}
          />
          <MessageInput onMessageSend={onMessageSend} />
        </div>
      </PopupWrapper>
    </DraggableContainer>
  );
}

interface MessageFeedProps {
  messages: Array<{
    id: string;
    senderId: string;
    senderName?: string;
    content: string;
    timestamp: Date | string;
  }>;
  currentUserId: string;
  isLoading?: boolean;
}

function MessageFeed({ messages, currentUserId, isLoading }: MessageFeedProps) {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const prevMessageCountRef = useRef(0);

  console.log("[MessageFeed] Rendering with currentUserId:", currentUserId);
  console.log("[MessageFeed] Messages:", messages.map(m => ({
    id: m.id,
    senderId: m.senderId,
    isFromMe: m.senderId === currentUserId,
    content: m.content.substring(0, 20)
  })));

  // Умный скролл - только при добавлении новых сообщений
  useEffect(() => {
    const currentCount = messages.length;

    // Скроллим только если добавилось новое сообщение
    if (
      currentCount > prevMessageCountRef.current &&
      prevMessageCountRef.current > 0
    ) {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }

    // Обновляем счетчик
    prevMessageCountRef.current = currentCount;
  }, [messages.length]); // Зависимость только от длины, не от всего массива

  return (
    <div
      className="flex flex-col w-full 2xl:h-[calc(100%-4.444vw)] h-full bg-[#F0F0F0] 2xl:p-[1.111vw] p-4 pb-0 overflow-y-auto [-webkit-scrollbar]:hidden"
      style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
    >
      {isLoading ? (
        <div className="flex justify-center items-center m-auto w-full">
          <span className="text-center text-gray-500 text-s">
            Загрузка истории чата...
          </span>
        </div>
      ) : messages.length === 0 ? (
        <div className="w-full flex flex-col 2xl:gap-[1.667vw] gap-6 items-center justify-center 2xl:px-[2.778vw] px-10 m-auto">
          <img
            src="/img/popups/EmptyMessageFeed.svg"
            className="2xl:size-[8.333vw] size-[120px]"
          />
          <span className="text-center text-s">
            Здесь пока нет сообщений. <br /> Можно начать беседу с приветствия
          </span>
        </div>
      ) : (
        <div className="flex flex-col 2xl:gap-[1.111vw] gap-4 items-end mt-auto">
          {messages.map((message) => (
            <MessageItem
              key={message.id}
              content={message.content}
              timestamp={new Date(message.timestamp).toLocaleTimeString(
                "ru-RU",
                {
                  hour: "2-digit",
                  minute: "2-digit",
                }
              )}
              isFromMe={message.senderId === currentUserId}
              senderName={message.senderName}
            />
          ))}

          {/* <MessageItem content="test" timestamp="12:00" isFromMe={false} />
          <MessageItem content="test123" timestamp="12:00" isFromMe={true} />
          <MessageItem content="testqwe" timestamp="12:00" isFromMe={true} />
          <MessageItem
            content={`asdasdasd\nasdasda\nasdasd`}
            timestamp="12:00"
            isFromMe={false}
          /> */}
          <div ref={messagesEndRef} />
        </div>
      )}
    </div>
  );
}

interface MessageItemProps {
  timestamp: string;
  content: string;
  isFromMe: boolean;
  senderName?: string;
}

function MessageItem({
  timestamp,
  content,
  isFromMe,
  senderName,
}: MessageItemProps) {
  return (
    <div
      className={clsx(
        "flex w-full items-end 2xl:gap-[0.556vw] gap-2 justify-end",
        isFromMe ? "" : "flex-row-reverse"
      )}
    >
      <div
        className={clsx(
          "2xl:p-[1.111vw] p-4 2xl:w-[16.667vw] w-[240px] flex items-end justify-between",
          isFromMe
            ? "bg-[#7B60F3] 2xl:rounded-[1.111vw_1.111vw_0_1.111vw] rounded-[16px_16px_0_16px] text-white"
            : "bg-[#FFFFFF] 2xl:rounded-[1.111vw_1.111vw_1.111vw_0] rounded-[16px_16px_16px_0] text-[#141414]"
        )}
      >
        <div className="break-words text-s 2xl:space-y-[0.278vw] space-y-1">
          {!isFromMe && (
            <div className="caption-s text-[#7B60F3]">
              {senderName || "Гость"}
            </div>
          )}
          <div className="whitespace-pre-wrap">{content}</div>
        </div>
        <span className="opacity-30 caption-xs">{timestamp}</span>
      </div>

      <div className="2xl:size-[2.222vw] size-8 rounded-full">
        <img
          src="/img/popups/MessageUserPfp.png"
          className="object-cover size-full"
          alt="user"
        />
      </div>
    </div>
  );
}

function MessageInput({
  onMessageSend,
}: {
  onMessageSend: (message: string) => void;
}) {
  const [message, setMessage] = useState("");
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    textarea.style.height = "auto";

    const computedStyle = window.getComputedStyle(textarea);
    const lineHeight = parseInt(computedStyle.lineHeight);
    const maxHeight = lineHeight * 4;
    const newHeight = Math.min(textarea.scrollHeight, maxHeight);

    textarea.style.height = `${newHeight}px`;
    textarea.style.overflowY =
      textarea.scrollHeight > maxHeight ? "auto" : "hidden";
  }, [message]);

  function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
    setMessage(e.target.value);
  }

  function sendMessage() {
    setMessage("");
    onMessageSend(message);
  }

  return (
    <div
      onClick={() => textareaRef.current?.focus()}
      className="flex w-full 2xl:min-h-[4.444vw] min-h-16 2xl:p-[1.111vw] p-4 items-end justify-between bg-white"
    >
      <textarea
        ref={textareaRef}
        value={message}
        onChange={handleChange}
        className="w-[80%] resize-none focus:outline-none my-auto text-s"
        rows={1}
        placeholder="Сообщение..."
      />
      <Button
        size="small"
        variant="cta"
        disabled={message.length === 0}
        onClick={sendMessage}
      >
        <div className="2xl:size-[1.111vw] size-4">
          <SendIcon />
        </div>
      </Button>
    </div>
  );
}
