import { Layout } from "antd";
import { t } from "i18next";
import { useUnmount } from "ahooks";
import { DragEvent, useRef, useState } from "react";

import { useConversationStore } from "@/store";
import { canSendImageTypeList, feedbackToast } from "@/utils/common";

import ChatContent from "./ChatContent";
import ChatFooter from "./ChatFooter";
import { useFileMessage } from "./ChatFooter/SendActionBar/useFileMessage";
import ChatHeader from "./ChatHeader";
import useConversationState from "./useConversationState";
import { useSendMessage } from "./ChatFooter/useSendMessage";

export const QueryChat = () => {
  const [dropVisible, setDropVisible] = useState(false);
  const dragDepth = useRef(0);

  const updateCurrentConversation = useConversationStore(
    (state) => state.updateCurrentConversation,
  );

  const { getImageMessage, getFileMessage } = useFileMessage();
  const { sendMessage } = useSendMessage();

  useConversationState();

  useUnmount(() => {
    updateCurrentConversation();
  });

  const onDragEnter = (e: DragEvent) => {
    if (!e.dataTransfer.types.includes("Files")) return;
    e.preventDefault();
    dragDepth.current += 1;
    setDropVisible(true);
  };

  const onDragOver = (e: DragEvent) => {
    if (!e.dataTransfer.types.includes("Files")) return;
    e.preventDefault();
  };

  const onDragLeave = (e: DragEvent) => {
    if (!e.dataTransfer.types.includes("Files")) return;
    dragDepth.current -= 1;
    if (dragDepth.current <= 0) {
      dragDepth.current = 0;
      setDropVisible(false);
    }
  };

  const onDrop = async (e: DragEvent) => {
    if (!e.dataTransfer.types.includes("Files")) return;
    e.preventDefault();
    dragDepth.current = 0;
    setDropVisible(false);

    const files = Array.from(e.dataTransfer.files);
    for (const file of files) {
      const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
      const isImage =
        file.type.startsWith("image/") || canSendImageTypeList.includes(ext);
      try {
        const message = isImage
          ? await getImageMessage(file)
          : await getFileMessage(file);
        sendMessage({ message });
      } catch (error) {
        feedbackToast({ error });
      }
    }
  };

  return (
    <Layout
      id="chat-container"
      className="relative overflow-hidden"
      onDragEnter={onDragEnter}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
      onDrop={onDrop}
    >
      <ChatHeader />
      <div className="flex min-h-0 flex-1 flex-col">
        <ChatContent />
      </div>
      <ChatFooter />
      {dropVisible && (
        <div className="pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-[rgba(0,115,217,0.12)]">
          <div className="rounded-lg bg-white px-8 py-4 text-sm shadow-lg">
            {t("placeholder.dropToSend")}
          </div>
        </div>
      )}
    </Layout>
  );
};
