import { useCallback, useState } from "react";
import { Button, DialogActions, DialogTitle, IconButton, Typography } from "@mui/material";
import Iconify from "@/shared/components/iconify";
import Dialog from "@mui/material/Dialog";
import ChatHeaderCompose from "./chat-header-compose";
import { IChatMessage, IClient } from "@/shared/types/chat";
import { useGetContactsTest, useGetConversation } from "@/shared/api/chat javalin";
import { addMinutes, format, sub } from 'date-fns';
import { useMockedUser, useSearchParams } from "@/hooks";
import useWebSocket from "react-use-websocket";
import uuidv4 from "@/utils/uuidv4";
import { mutateConversation, mutateConversations } from "@/shared/api/chatv2";


type Props = {
  isOpen: any;
  onClose: () => void;
  message: IChatMessage;
};

export default function ChatTransferDialog({
  isOpen,
  onClose,
  message,
}: Props) {
  const [driverName, setDriverName] = useState("");
  const { contacts } = useGetContactsTest();
  const [recipients, setRecipients] = useState<IClient[]>([]);
  const { user1 } = useMockedUser();
  const searchParams = useSearchParams();
  const selectedConversationId = searchParams.get('id') || '';


const { sendMessage ,lastMessage,readyState} = useWebSocket("ws://localhost:4000/chat", {
    queryParams: {

      "id": `${user1.uuid}`,
    },
    onOpen: () => {
      
      console.log('WebSocket connection established.');
      console.log("user uuid "+ user1.uuid);

    },
    onClose: (event) => {
      console.log("session closed", event)
    },
    onError: (event) => {
      console.log("session error", event)
    }
});


  const handleAddRecipients = useCallback((selected: IClient[]) => {
    setRecipients(selected);
  }, []);

  const handleTransfer = () => {
    onTransfer(message, recipients);
    onClose(); // Close the dialog after transfer
  };
  const myContact : IClient = {
    id: user1?.id,
    uuid: `${user1?.uuid}`,
    usernameType : 'EMAIL',
    username : `${user1?.username}`,
    firstname: `${user1?.firstname}`,
    lastname: `${user1?.lastname}`,
    avatarUrl:`${user1?.avatarUrl}`,
    phoneNumber:'', 
    status : 'online' as 'online' | 'offline',
    lastActivity: new Date(),
  }



 /*  const onTransfer = async (message: IChatMessage, recipients: IClient[]) => {
    recipients.forEach(recipient => {
      const formatDate = (date: Date) => format(date, "yyyy-MM-dd'T'HH:mm:ss.SSS");
  
      const response = await fetch('http://localhost:4000/conversation/by-participants', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          participant1Uuid: myContact.uuid,
          participant2Uuid: recipient.uuid,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to get or create conversation');
      }

      const data = await response.json();
      const conversationId = data.conversationId;
      const currentDate = new Date();
      const newDate = formatDate(addMinutes(currentDate, 1));
  
      const transferMessageObject = {
        sourceUuid: myContact.uuid,
        destinationUuid: recipient.uuid, // Sending to each selected recipient
        type: message.type,
        body: message.body,
        date: newDate,
        uuid: uuidv4(),
        replyTo: null,
      };
  
   
      // Optionally, update the conversation state locally
     // mutateConversation(recipient.conversationId, transferMessageObject);
      mutateConversations(user1.id, "943a25b9-a08a-49b9-95e0-eb3a7aa18d7f", transferMessageObject);
      sendMessage(JSON.stringify(transferMessageObject));

    });
  }; */
  
  const onTransfer = async (message: IChatMessage, recipients: IClient[]) => {
    const formatDate = (date: Date) => format(date, "yyyy-MM-dd'T'HH:mm:ss.SSS");
    const currentDate = new Date();
    const newDate = formatDate(addMinutes(currentDate, 1));
  
    for (const recipient of recipients) {
      try {
        console.log("me : "+user1.uuid);
        console.log("recipient : "+recipient.uuid);

        // Step 1: Get or create conversation ID by calling the backend
        const response = await fetch('http://localhost:4000/conversation/by-participants', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            participant1Uuid: user1.uuid,
            participant2Uuid: recipient.uuid,
          }),
        });
  
        if (!response.ok) {
          throw new Error('Failed to get or create conversation');
        }
  
       
        const data = await response.json();
        const conversationId = data.conversationId;

        // Step 2: Create the transfer message object
        const transferMessageObject = {
          sourceUuid: user1.uuid,
          destinationUuid: recipient.uuid, // Sending to each selected recipient
          type: message.type,
          body: message.body,
          date: newDate,
          uuid: uuidv4(),
          replyTo: null,
          conversation: conversationId, // Set the conversation ID
        };
  
        // Step 3: Optionally update the conversation state locally
        mutateConversations(user1.id, conversationId, transferMessageObject);
  
        // Step 4: Send the message via WebSocket
        sendMessage(JSON.stringify(transferMessageObject));
      } catch (error) {
        const errorMessage = (error as Error).message;
        console.error('Error transferring message:', errorMessage);
      }
    }
  };
  
  return (
    <Dialog fullWidth maxWidth="sm" open={isOpen} onClose={onClose}>
      <DialogTitle sx={{ m: 0, p: 2, backgroundColor: "#f5f5f5" }}>
        Share message to
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{
            position: "absolute",
            right: 8,
            top: 8,
            color: "text.secondary",
          }}
        >
          <Iconify icon="ri:close-fill" />
        </IconButton>
      </DialogTitle>

      <ChatHeaderCompose
        onAddRecipients={handleAddRecipients}
      >
        <Typography
          variant="subtitle2"
          sx={{ color: "text.primary", mr: 2 }}
        ></Typography>
      </ChatHeaderCompose>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button onClick={handleTransfer} color="primary">Transfer</Button>
      </DialogActions>
          </Dialog>
  );
}
