/* eslint-disable react-hooks/rules-of-hooks */
"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import useAxios from "@/hooks/useAxios";
import { User } from "@/types/types";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import React, { useState, useEffect, useRef } from "react";
import MessageList from "@/components/chat/MessageList";
import ImageModal from "@/components/chat/ImageModal";
import TicketInput from "@/components/settings/ticket/MessageInput";

interface ITicketChatProps {
  params: Promise<{ id: string; title: string }>;
}

function TicketChat({ params }: ITicketChatProps) {
  const resolvedParams = React.use(params);
  const { request } = useAxios();
  const { id, title } = resolvedParams;
  const decodedTitle = decodeURIComponent(title);
  const [newMessage, setNewMessage] = useState<string>("");
  const [userDetail, setUserDetail] = useState<User>();
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [showModal, setShowModal] = useState<boolean>(false);
  const messagesEndRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const fetchStates = async () => {
      const response = await request<{ user: User }>("GET", "/profile");
      setUserDetail(response?.user);
    };
    fetchStates();
  }, []);

  const { refetch } = useInfiniteScroll({
    endpoint: "/tickets/messages",
    queryKey: ["messages", id],
    params: { ticketId: id },
  });

  const handleImageSelection = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedImage(file);
      setShowModal(true);
    }
  };

  const cancelImage = () => {
    setSelectedImage(null);
    setShowModal(false);
  };

  const confirmImage = () => {
    setShowModal(false);
    sendMessage();
  };

  const sendMessage = async () => {
    if (newMessage.trim() === "" && !selectedImage) return;
    const formData = new FormData();
    formData.append("text", newMessage);
    formData.append("ticketId", id);
    formData.append("senderId", userDetail?._id ? userDetail?._id : "");
    if (selectedImage) {
      formData.append("file", selectedImage);
    }
    try {
      await request("post", `/tickets/message?ticketId=${id}`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      setNewMessage("");
      setSelectedImage(null); // Reset image after sending
      refetch(); // Fetch new data after sending message
    } catch (error) {
      console.error("Error sending message:", error);
    }
  };

  return (
    <Container>
      <PageTitle>{decodedTitle}</PageTitle>
      <MessageList id={id} userDetail={userDetail} refetch={refetch} />
      <TicketInput
        newMessage={newMessage}
        setNewMessage={setNewMessage}
        sendMessage={sendMessage}
        handleImageSelection={handleImageSelection}
      />
      <ImageModal
        isOpen={showModal}
        selectedImage={selectedImage}
        cancelImage={cancelImage}
        confirmImage={confirmImage}
      />
      <div ref={messagesEndRef} />
    </Container>
  );
}

export default TicketChat;
