"use client"

import {
  MessageListConfiguration,
  CometChatMessages,
  CometChatMessageTemplate,
  CometChatUIKit,
  CometChatUIKitConstants,
  ThreadedMessagesConfiguration,
  CometChatGroups,
  CometChatTheme,
  CometChatConversationsWithMessages,
  ConversationsConfiguration,
  MessagesConfiguration,
  ContactsConfiguration,
  UsersConfiguration,
  ListItemStyle,
  CometChatContacts,
} from "@cometchat//chat-uikit-react"
import classNames from "classnames"
import { ChatGroupCss } from "./style"
import { useEffect, useRef, useState } from "react"
import { CometChat } from "@cometchat/chat-sdk-javascript"
import { Avatar } from "antd"
import dayjs from "dayjs"
import Link from "next/link"
import React from "react"
import { useRecoilValue } from "recoil"
import { loggedInUserState } from "@/recoil"
import Image from "next/image"
import NotFoundBox from "../../Notfound"
import CreateGroup from "./CreateGroup"
import { CustomCometChatTheme } from "../Common"

type IProps = {
  friendsOnly?: boolean
  openDrawer: boolean
  loading?: boolean
  setOpenDrawer: (isOpen: boolean) => void
}

export default function ChatGroups({ friendsOnly = false, openDrawer, loading, setOpenDrawer }: IProps) {
  const loggedInUser = useRecoilValue(loggedInUserState)
  // const [chatGroup, setChatGroup] = useState<CometChat.Group>()
  const [templates, setTemplates] = useState<CometChatMessageTemplate[]>([])
  const [isMobile, setIsMobile] = useState<boolean>(false)

  useEffect(() => {
    const updateTabPosition = () => {
      setIsMobile(window.innerWidth <= 768 ? true : false)
    }
    updateTabPosition()
    window.addEventListener("resize", updateTabPosition)

    return () => {
      window.removeEventListener("resize", updateTabPosition)
    }
  }, [])

  // const getListItemView = (group: CometChat.Group) => {
  //   if (group.getHasJoined()) {
  //     return (
  //       <div
  //         className={`relative flex p-2.5 mb-2 rounded-[10px] border solid ${
  //           chatGroup?.getGuid() === group.getGuid()
  //             ? "bg-[var(--primary--10)] border-[var(--primary--70)]"
  //             : "bg-[var(--secondary-10)] border-[var(--secondary-20)]"
  //         }`}>
  //         <Link
  //           href="#"
  //           scroll={false}
  //           className="absolute w-full h-full z-10 top-0 left-0"
  //           onClick={() => {
  //             setChatGroup(group)
  //           }}></Link>
  //         <div className="relative">
  //           <Avatar
  //             src={group.getIcon()}
  //             alt={group.getName()}
  //             size={52}>
  //             {group.getName() && group.getIcon() === undefined ? group.getName().slice(0, 2).toUpperCase() : "G"}
  //           </Avatar>
  //         </div>

  //         <div className="pl-2.5 flex flex-col justify-center">
  //           <div className="text-sm font-semibold text-[var(--secondary-100)] h-5 line-clamp-1">{group.getName()}</div>
  //           <div className="text-sm font-light text-[var(--secondary-100)] h-5 line-clamp-1">
  //             <span className="mr-2">{`${group.getMembersCount()} Members`}</span>
  //           </div>
  //         </div>
  //       </div>
  //     )
  //   }

  //   return <div className="hidden"></div>
  // }

  // useEffect(() => {
  //   const fetchDefaultUser = async () => {
  //     try {
  //       const limit = 1
  //       const groupsRequest = new CometChat.GroupsRequestBuilder().setLimit(limit).joinedOnly(true).build()

  //       const Groups = await groupsRequest.fetchNext()

  //       if (Groups && Groups.length > 0) {
  //         setChatGroup(Groups[0])
  //       }
  //     } catch (error) {
  //       console.error("Failed to fetch default user:", error)
  //     }
  //   }

  //   fetchDefaultUser()
  // }, [])

  useEffect(() => {
    const _theme = new CometChatTheme({})
    const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(_theme)
    const template = definedTemplates?.map((templates, index) => {
      if (templates.type === "text" && templates.category === CometChatUIKitConstants.MessageCategory.message) {
        templates.contentView = (message: CometChat.BaseMessage) => getContentView(message)
        templates.statusInfoView = (message: CometChat.BaseMessage) => getStatusInfo(message)
        return templates
      }
      return templates
    })
    setTemplates(template)
  }, [])

  const getContentView = (message: CometChat.BaseMessage) => {
    if (loggedInUser?.uid === message?.getSender()?.getUid()) {
      return (
        <div className="text-sm leading-[22px] p-2.5 rounded-tl-[10px] text-white rounded-tr-[10px] bg-[var(--secondary-100)] custom_mess_send_box">
          {message?.getData().text || ""}
        </div>
      )
    }

    return (
      <div className="flex flex-col px-2.5 pt-2.5 pb-0.5 bg-white custom_mess_receive_box">
        <div className="text-sm leading-[18px] font-semibold text-[var(--secondary-100)]">{message?.getSender()?.getName()}</div>
        <div className="text-sm leading-[22px] font-normal text-[var(--secondary-60)]">{message?.getData().text || ""}</div>
      </div>
    )
  }

  const getStatusInfo = (message: CometChat.BaseMessage) => {
    if (message instanceof CometChat.TextMessage) {
      const isRead = message?.getReadAt()
      const timestamp = message?.getDeliveredAt() || message?.getSentAt()
      const date = new Date(timestamp * 1000)
      const formattedTime = dayjs(date).format("HH:mm")

      return (
        <div
          className={`flex justify-between gap-4 px-2.5 pb-2.5 ${
            loggedInUser?.uid === message?.getSender()?.getUid() ? "text-white" : "text-[var(--secondary-50)"
          }`}>
          <span>{formattedTime}</span>
          <div className="flex">
            <Image
              src={`${loggedInUser?.uid === message?.getSender()?.getUid() ? "/img/icon/tow_checkmark_done_white.svg" : "/img/icon/two_checkmark_done.svg"}`}
              alt={`${"tow_checkmark_done"}`}
              width={300}
              height={300}
              className={`w-full aspect-square`}
            />
            <span className={`${loggedInUser?.uid === message?.getSender()?.getUid() ? "text-white" : "text-[var(--success-80)]"}`}>
              {isRead ? "Seen" : "Sent"}
            </span>
          </div>
        </div>
      )
    }

    return null
  }

  const messageListConfiguration = new MessageListConfiguration({
    templates: templates,
    scrollToBottomOnNewMessages: true,
  })

  const threadedMessagesConfiguration = new ThreadedMessagesConfiguration({
    messageListConfiguration,
  })

  // CometChatConversationsWithMessages

  const listItemStyle = new ListItemStyle({
    activeBackground: "#ffedc9",
    hoverBackground: "#fffdf3",
    titleColor: "#030712",
    padding: "12px 2px",
    borderRadius: "8px 8px 0 0",
  })
  const emptyStateView = (
    <NotFoundBox
      backHome={false}
      message="No groups found"
    />
  )
  const conversationsRequestBuilder = new CometChat.ConversationsRequestBuilder().setConversationType("group").setLimit(50)

  if (friendsOnly) {
    conversationsRequestBuilder.setUserTags(["friend"])
  }

  const conversationsConfiguration = new ConversationsConfiguration({
    listItemStyle,
    emptyStateView,
    conversationsRequestBuilder,
  })

  const messagesConfiguration = new MessagesConfiguration({
    messageListConfiguration: messageListConfiguration,
    threadedMessageConfiguration: threadedMessagesConfiguration,
  })

  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      let target = event.target as HTMLElement | null;
  
      while (target) {
        if (target.tagName === "COMETCHAT-BUTTON") {
          setTimeout(() => {
            const wrapper1 = document.querySelector(".cc-contacts-wrapper");
            const secondTabItem = wrapper1?.querySelectorAll(".cc-tab-item")[1];
  
            if (secondTabItem) {
              const iconButton = secondTabItem.querySelector("cometchat-icon-button") as HTMLElement;
              const shadowRoot = (iconButton as any)?.shadowRoot;
              const button = shadowRoot?.querySelector(".cc__iconbutton");
  
              if (button instanceof HTMLButtonElement) {
                button.click();
              }
            }
          }, 500);
          break;
        }
        target = target.parentElement;
      }
    };
  
    document.addEventListener("click", handleClick);
    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, []);
  

  return (
    <div className={classNames("h-full md:flex rounded-[10px] items-stretch custom_group_ms", ChatGroupCss)}>
      {/* Start CometChatConversationsWithMessages */}
      <CometChatConversationsWithMessages
        conversationsConfiguration={conversationsConfiguration}
        messagesConfiguration={messagesConfiguration}
        isMobileView={isMobile}
      />
      {/* End CometChatConversationsWithMessages */}

      {/* <div className="md:w-1/2 lg:w-1/3 xl:w-1/4 shrink-0 h-96 overflow-y-auto md:h-auto pb-8 md:pb-0">
        <CometChatGroups
          listItemView={getListItemView}
          searchPlaceholderText="Search chat name"
          emptyStateView={
            <NotFoundBox
              backHome={false}
              message="No groups found"
            />
          }
        />
      </div>
      <div className="md:grow h-96 md:h-auto relative">
        <CustomCometChatTheme
          children={
            <CometChatMessages
              group={chatGroup}
              messageListConfiguration={messageListConfiguration}
              threadedMessagesConfiguration={threadedMessagesConfiguration}
            />
          }
        />
      </div> */}
      <CreateGroup
        openDrawer={openDrawer}
        setOpenDrawer={setOpenDrawer}
        loading={loading}
      />
    </div>
  )
}
