import { useState } from "react";
import useAxios from "axios-hooks";
import useMedia from "./useMedia";

const useMessaging = () => {
  const { handleUploadMedia, uploadMediaData } = useMedia();
  const [loading, setLoading] = useState();
  const affiliates = localStorage?.getItem("affiliates");

  //GET Retrieve message
  const [{ ...retrieveMessageData }, retrieveMessage] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );
  const handleRetrieveMessage = async (
    account_id,
    course_id,
    room_id,
    limit,
    offset
  ) => {
    try {
      await retrieveMessage({
        url: `/notify/v1/chats/`,
        params: {
          account_id,
          course_id,
          room_id,
          limit,
          offset,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  //GET Read message
  const [{ ...ReadMessageData }, readMessage] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );
  const handleReadMessage = async (id) => {
    try {
      await readMessage({
        url: `/notify/v1/chats/${id}/read_message/`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //POST Create message personal
  const [{ ...createMessagePersonalData }, createMessagePersonal] = useAxios(
    {
      method: "POST",
    },
    {
      manual: true,
    }
  );

  const handleCreateMessagePersonal = async (account_id, data, course_id) => {
    await createMessagePersonal({
      url: `/notify/v1/chats/`,
      data: {
        ...data,
      },
      params: {
        account_id,
        course_id,
        // room_id,
      },
    });
  };

  //POST Create message
  const [{ ...createMessageData }, createMessage] = useAxios(
    {
      method: "POST",
    },
    {
      manual: true,
    }
  );

  const handleCreateMessage = async (
    account_id,
    account_type,
    data,
    course_id,
    enterprise_account_id
  ) => {
    let apiUrl;

    if (account_type === "instructor") {
      // For instructor account type
      apiUrl = enterprise_account_id
        ? `/notify/v1/instructor/${enterprise_account_id}/chats/` // Affiliate instructor
        : `/notify/v1/${account_type}/chats/`; // Non-affiliate instructor
    } else if (account_type === "enterprise") {
      // For enterprise account type
      apiUrl = `/notify/v1/${account_type}/chats/`; // Enterprise
    } else if (account_type === "personal") {
      // For personal account type
      apiUrl = `/notify/v1/chats/`;
    } else {
      // throw new Error("Invalid account type"); // Optional error handling for unexpected types
      console.log("Invalid account type");
    }

    await createMessage({
      url: apiUrl,
      data: {
        ...data,
      },
      params: {
        account_id,
        course_id,
        // room_id,
      },
    });
  };

  //POST Create message Affiliate
  const [{ ...createMessageAffiliateData }, createMessageAffiliate] = useAxios(
    {
      method: "POST",
    },
    {
      manual: true,
    }
  );

  const handleCreateMessageAffiliate = async (
    account_id,
    account_type,
    data,
    course_id
  ) => {
    await createMessageAffiliate({
      url: `/notify/v1/${account_type}/${account_id}/chats/`,
      data: {
        ...data,
      },
      params: {
        account_id,
        course_id,
        // room_id,
      },
    });
  };

  //POST Create message with media
  const [{ ...createMessageWithMediaData }, createMessageMedia] = useAxios(
    {
      method: "POST",
    },
    {
      manual: true,
    }
  );

  const handleCreateMessageWithMedia = async (
    account_id,
    account_type,
    file,
    course_id,
    enterprise_account_id
  ) => {
    setLoading(true);
    const newUploaded = [];

    const formData = new FormData();
    formData.append("upload", file);
    const uploadedData = await handleUploadMedia(formData, account_type, enterprise_account_id);

    newUploaded.push(uploadedData?.data?.results[0]);

    let apiUrl;

    if (account_type === "instructor") {
      // For instructor account type
      apiUrl = enterprise_account_id
        ? `/notify/v1/instructor/${enterprise_account_id}/chats/` // Affiliate instructor
        : `/notify/v1/${account_type}/chats/`; // Non-affiliate instructor
    } else if (account_type === "enterprise") {
      // For enterprise account type
      apiUrl = `/notify/v1/${account_type}/chats/`; // Enterprise
    } else if (account_type === "personal") {
      // For personal account type
      apiUrl = `/notify/v1/chats/`;
    } else {
      console.log("Invalid account type");
    }

    // if (uploadMediaData?.data) {
    await createMessageMedia({
      url: apiUrl,
      data: {
        // ...data,
        ...(newUploaded?.length && {
          media: newUploaded?.[0],
        }),
      },
      params: {
        account_id,
        course_id,
      },
    });
    // }
  };

  //GET Room Messages
  const [{ ...roomMessageData }, roomMessage] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomMessage = async (
    account_type,
    account_id,
    course_id,
    room_id,
    limit,
    offset
  ) => {
    try {
      await roomMessage({
        url: `/notify/v1/${account_type}/chats/`,
        params: {
          account_id,
          course_id,
          room_id,
          limit,
          offset,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  //GET Room Messages Affiliate
  const [{ ...roomMessageAffiliateData }, roomMessageAffiliate] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomMessageAffiliate = async (
    account_id,
    course_id,
    room_id,
    enterprise_account_id,
    limit,
    offset
  ) => {
    try {
      await roomMessageAffiliate({
        url: `/notify/v1/instructor/${enterprise_account_id}/chats/`,
        params: {
          account_id,
          course_id,
          room_id,
          limit,
          offset,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  const [
    { ...roomRecipientDetailsAffiliateData },
    roomRecipientDetailsAffiliate,
  ] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomRecipientDetailsAffiliate = async (
    enterprise_account_id,
    account_id,
    course_id
  ) => {
    try {
      await roomRecipientDetailsAffiliate({
        url: `/notify/v1/instructor/${enterprise_account_id}/chats/recipient_details/`,
        params: {
          account_id,
          course_id,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  //GET Room Messages for Recipient
  const [{ ...roomMessageRecipientData }, roomMessageRecipient] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomMessageRecipient = async (room_id, recipient_only = true) => {
    try {
      await roomMessageRecipient({
        url: `/notify/v1/chats/`,
        params: {
          room_id,
          recipient_only,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  //DELETE message
  const [{ ...deleteMessageData }, deleteMessage] = useAxios(
    {
      method: "DELETE",
    },
    {
      manual: true,
    }
  );

  const handleDeleteMessage = async (id) => {
    try {
      await deleteMessage({
        url: `/notify/v1/chats/${id}/`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //Clear chats/rooms
  const [{ ...clearChatData }, clearChat] = useAxios(
    {
      method: "DELETE",
    },
    {
      manual: true,
    }
  );

  const handleClearChat = async (account_type, id) => {
    try {
      await clearChat({
        url: `/notify/v1/${account_type}/rooms/${id}/`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //Clear chats/rooms Affiliate
  const [{ ...clearChatAffiliateData }, clearChatAffiliate] = useAxios(
    {
      method: "DELETE",
    },
    {
      manual: true,
    }
  );

  const handleClearChatAffiliate = async (enterprise_account_id, room_id) => {
    try {
      await clearChatAffiliate({
        url: `/notify/v1/instructor/${enterprise_account_id}/rooms/${room_id}/`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //Clear chats/rooms personal
  const [{ ...clearChatPersonalData }, clearChatPersonal] = useAxios(
    {
      method: "DELETE",
    },
    {
      manual: true,
    }
  );

  const handleClearChatPersonal = async (room_id) => {
    try {
      await clearChatPersonal({
        url: `/notify/v1/rooms/${room_id}/`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //POST report user
  const [{ ...reportUserData }, reportUser] = useAxios(
    {
      method: "POST",
    },
    {
      manual: true,
    }
  );

  const handleReportUser = async (account_type, data) => {
    try {
      await reportUser({
        url: `/notify/v1/${account_type}/chats/reports/`,
        data: {
          ...data,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  //GET Room Messages for Recipient

  const [{ ...roomRecipientDetailsData }, roomRecipientDetails] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomRecipientDetails = async (
    account_type,
    account_id,
    course_id,
    recipient_only = true
  ) => {
    try {
      await roomRecipientDetails({
        url: `/notify/v1/${account_type}/chats/recipient_details/`,
        params: {
          // room_id,
          account_id,
          course_id,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  const [
    { ...roomRecipientDetailsPersonalData },
    roomRecipientDetailsPersonal,
  ] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );

  const handleRoomRecipientDetailsPersonal = async (account_id, course_id) => {
    try {
      await roomRecipientDetailsPersonal({
        url: `/notify/v1/chats/recipient_details/`,
        params: {
          account_id,
          course_id,
          // room_id,
        },
      });
    } catch (err) {
      console.log(err);
    }
  };

  return {
    retrieveMessageData,
    handleRetrieveMessage,
    ReadMessageData,
    handleReadMessage,
    createMessageData,
    handleCreateMessage,
    deleteMessageData,
    handleDeleteMessage,
    reportUserData,
    handleReportUser,
    roomMessageData,
    handleRoomMessage,
    createMessageWithMediaData,
    handleCreateMessageWithMedia,
    clearChatData,
    handleClearChat,
    roomMessageRecipientData,
    handleRoomMessageRecipient,
    roomRecipientDetailsData,
    handleRoomRecipientDetails,
    createMessageAffiliateData,
    handleCreateMessageAffiliate,
    roomMessageAffiliateData,
    handleRoomMessageAffiliate,
    roomRecipientDetailsPersonalData,
    handleRoomRecipientDetailsPersonal,
    createMessagePersonalData,
    handleCreateMessagePersonal,
    clearChatPersonalData,
    handleClearChatPersonal,
    clearChatAffiliateData,
    handleClearChatAffiliate,
    roomRecipientDetailsAffiliateData,
    handleRoomRecipientDetailsAffiliate,
  };
};

export default useMessaging;
