import { Box, IconButton, Stack, Typography, useTheme } from "@mui/material";
import Iconify from "@/shared/components/iconify";
import ChatHeaderCompose from "./chat-header-compose";
import { useGetContactsTest ,useGetConversation} from "@/shared/api/chat javalin";
import { useCollapseNav, useMockedUser, useResponsive, useSearchParams } from "@/hooks";
import React, { useCallback, useEffect, useState } from "react";
import { IChatParticipant, IClient,IChatMessage } from "@/shared/types/chat";
import ChatMessageList from "./chat-message-list";
import ChatMessageInput from "./chat-message-input";


type Props = {
    children:React.ReactNode;
};
export default function ChatNewMessage(children:Props){


 ////////////////////////////////
  const {
    collapseDesktop,
    onCloseDesktop,
    onCollapseDesktop,
    //
    openMobile,
    onOpenMobile,
    onCloseMobile,
  } = useCollapseNav();

  const mdUp = useResponsive('up', 'md');

  useEffect(() => {
    if (!mdUp) {
      onCloseMobile();
    }else{
      onCloseDesktop();
      onOpenMobile();
    }
  }, [onCloseDesktop, mdUp]);

  ///////////////////////////////////////

    const { user1 } = useMockedUser();

    const searchParams = useSearchParams();

    const { contacts } = useGetContactsTest();

    const selectedConversationId = searchParams.get('id') || '';

    const [recipients, setRecipients] = useState<IClient[]>([]);

    const { conversation, conversationError } = useGetConversation(`${selectedConversationId}`);
    const [messages, setMessages] = useState<IChatMessage[]>([]);

    const participants: IClient[] = conversation
    ? conversation.participants.filter(
        (participant: IClient) => participant.uuid !== `${user1?.id}`
      )
    : [];

    const [replyTo, setReplyTo] = useState<IChatMessage | null>(null); // State to track the message being replied to

    const handleReplyMessage = (message: IChatMessage | null) => {
      setReplyTo(message); // Set the message being replied to
    };
    useEffect(() => {
      if (conversation && conversation.messages) {
        setMessages(conversation.messages);
      }else{
        setMessages([]);
      }
    }, [conversation]);

    const handleNewMessage = useCallback((newMessage: IChatMessage) => {
      setMessages((prevMessages) => [...prevMessages, newMessage]);
    }, []);
    const handleAddRecipients = useCallback((selected: IClient[]) => {
        setRecipients(selected);
    }, []);


    const renderHead = ({ children }:Props) =>(
        <Stack
      direction="row"
      alignItems="center"
      flexShrink={0}
      sx={{ pl: 2, py: 1, minHeight: 72 }}
    >
        {children}
        <ChatHeaderCompose onAddRecipients={handleAddRecipients} >
          <Typography variant="subtitle2" sx={{ color: 'text.primary', mr: 2 }}>
            To :
          </Typography>
        </ChatHeaderCompose>
    </Stack>
    );

    const renderMessages = (
        <>
            <Stack
            sx={{
                width: 1,
                height: 1,
                overflow: 'hidden',
            }}
            >
            <ChatMessageList messages={conversation?.messages} participants={participants} selectedConversationid={conversation?.uuid} onReplyMessage={handleReplyMessage} replyMessage={replyTo}/>
            
            <ChatMessageInput
                recipients={recipients}
                onAddRecipients={handleAddRecipients}
                onClearReply={() => setReplyTo(null)}
                selectedConversationId={selectedConversationId}
                disabled={!recipients.length && !selectedConversationId}
                onNewMessage={handleNewMessage}
                replyTo={null}
                />
            </Stack>
        </>
      );

    
    return (
        <>
            <Stack
            sx={{
              width: 1,
              height: 'calc(100vh - 270px)',
              overflow: 'hidden',
            }}
            
            
          >
            {renderHead(children)}
  
            <Stack
              direction="row"
              sx={{
                width: 1,
                height: 1,
                overflow: 'hidden',
                borderTop: (theme) => `solid 1px ${theme.palette.divider}`,
              }}
            >
              {renderMessages}
  
            </Stack>
            </Stack>

        </>
    );
}