"use client"

import {
  CometChatUsers,
  MessageListConfiguration,
  CometChatMessages,
  CometChatMessageTemplate,
  CometChatUIKit,
  CometChatUIKitConstants,
  ThreadedMessagesConfiguration,
  CometChatTheme,
  CometChatConversationsWithMessages,
  CometChatContacts,
  ConversationsConfiguration,
  CometChatConversations,
  ListItemStyle,
  ConversationsStyle,
  WithMessagesStyle,
  MessagesConfiguration,
  ContactsConfiguration,
  UsersConfiguration,
} from "@cometchat//chat-uikit-react"
import classNames from "classnames"
import { ChatCss } from "./style"
import { useEffect, 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 { useRecoilState, useRecoilValue } from "recoil"
import { loggedInUserState } from "@/recoil"
import Image from "next/image"
import NotFoundBox from "../../Notfound"
import { CustomCometChatTheme } from "../Common"
import { chatUidCurrentState, isGoChatUidState } from "@/recoil/chat"
import { appConfig } from "@/config/app"
// import { CometChatMessageAction, CustomTypeCall, ITypeCallProps } from "../Common"

// interface ICustomCallCateProps extends Pick<ITypeCallProps, "type"> {
//   message: CometChat.BaseMessage
// }

type IProps = {
  friendsOnly?: boolean
}

export default function ChatRecent({ friendsOnly = false }: IProps) {
  const loggedInUser = useRecoilValue(loggedInUserState)
  const isGoChat = useRecoilValue<boolean>(isGoChatUidState)
  const [chatUser, setChatUser] = useRecoilState<CometChat.User>(chatUidCurrentState)
  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 = (user: CometChat.User) => {
  //   console.log("user", user)

  //   return (
  //     <div
  //       className={`relative flex p-2.5 mb-2 rounded-[10px] border solid ${
  //         chatUser?.getUid() === user.getUid() ? "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={() => {
  //           setChatUser(user)
  //         }}></Link>
  //       <div className="relative">
  //         <Avatar
  //           src={user.getAvatar()}
  //           alt={user.getName()}
  //           size={52}>
  //           {user.getName() && user.getAvatar() === undefined ? user.getName().slice(0, 2).toUpperCase() : "AC"}
  //         </Avatar>
  //         <span
  //           className={`absolute bottom-0 right-0 inline-block w-3 h-3 rounded-full border border-solid border-white ${
  //             user.getStatus() === "online" ? "bg-[var(--chat-user-online)]" : "bg-[var(--danger-50)]"
  //           }`}></span>
  //       </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">{user.getName()}</div>
  //         <div className="text-sm font-light text-[var(--secondary-100)] h-5 line-clamp-1">
  //           <span className="mr-2">{user.getStatus()}</span>
  //           {user.getLastActiveAt() ? dayjs.unix(user.getLastActiveAt()).format("MMM DD, YYYY HH:mm") : null}
  //         </div>
  //       </div>
  //     </div>
  //   )
  // }

  // useEffect(() => {
  //   const fetchDefaultUser = async () => {
  //     try {
  //       const limit = 1
  //       const usersRequest = new CometChat.UsersRequestBuilder().setLimit(limit).build()

  //       const users = await usersRequest.fetchNext()
  //       if (users && users.length > 0 && !isGoChat) {
  //         setChatUser(users[0])
  //       }
  //     } catch (error) {
  //       console.error("Failed to fetch default user:", error)
  //     }
  //   }

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

  useEffect(() => {
    const _theme = new CometChatTheme({})
    const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(_theme)
    const template = definedTemplates?.map((templates) => {
      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
      }
      // if ((templates.type === "audio" || templates.type === "video") && templates.category === CometChatUIKitConstants.MessageCategory.call) {
      //   templates.contentView = (message: CometChat.BaseMessage) => getCustomCallView({ message, type: templates?.type })
      // }
      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 getCustomCallView = (props: ICustomCallCateProps) => {
  //   const callStatus = props?.message?.getStatus()

  //   const actionMapping: Record<string, { senderAction: keyof typeof CometChatMessageAction; receiverAction: keyof typeof CometChatMessageAction }> = {
  //     initiated: { senderAction: "outgoing", receiverAction: "incoming" },
  //     cancelled: { senderAction: "cancelled", receiverAction: "missed" },
  //     rejected: { senderAction: "cancelled", receiverAction: "missed" },
  //     ended: { senderAction: "ended", receiverAction: "ended" },
  //   }

  //   const { senderAction, receiverAction } = actionMapping[callStatus] || {}

  //   if (senderAction !== undefined && receiverAction !== undefined) {
  //     const action = props?.message?.getSender()?.getUid() === loggedInUser.uid ? senderAction : receiverAction

  //     return (
  //       <CustomTypeCall
  //         action={action}
  //         type={props?.type}
  //       />
  //     )
  //   }

  //   return <CustomTypeCall type={"Invalid"} />
  // }

  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 users found"
    />
  )
  const conversationsRequestBuilder = new CometChat.ConversationsRequestBuilder().setConversationType("user").setLimit(50)

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

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

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

  const startConversationConfiguration = new ContactsConfiguration({
    usersConfiguration: new UsersConfiguration({
      usersRequestBuilder: friendsOnly ? new CometChat.UsersRequestBuilder().friendsOnly(friendsOnly).setLimit(100) : undefined,
      searchRequestBuilder: friendsOnly ? new CometChat.UsersRequestBuilder().setTags(["friend"]).setLimit(100) : undefined,
    }),
  })

  return (
    <div className={classNames("h-full md:flex rounded-[10px] items-stretch", ChatCss)}>
      {/* Start CometChatConversationsWithMessages */}
      <CometChatConversationsWithMessages
        conversationsConfiguration={conversationsConfiguration}
        messagesConfiguration={messagesConfiguration}
        startConversationConfiguration={startConversationConfiguration}
        isMobileView={isMobile}
        user={chatUser}
      />
      {/* 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">
        <CometChatUsers
          showSectionHeader={false}
          listItemView={getListItemView}
          searchPlaceholderText="Search chat name"
          usersRequestBuilder={friendsOnly ? new CometChat.UsersRequestBuilder().friendsOnly(friendsOnly).setLimit(100) : undefined}
          emptyStateView={
            <NotFoundBox
              backHome={false}
              message="No users found"
            />
          }
        />
      </div>
      <div className="md:grow h-96 md:h-auto relative">
        <CustomCometChatTheme
          children={
            <CometChatMessages
              user={chatUser}
              messageListConfiguration={messageListConfiguration}
              threadedMessagesConfiguration={threadedMessagesConfiguration}
            />
          }
        />
      </div> */}

      {/* <CometChatUsersWithMessages
        usersConfiguration={
          new UsersConfiguration({
            listItemView: getListItemView,
          })
        }
        messagesConfiguration={
          new MessagesConfiguration({
            messageHeaderView: {
              user: chatUser,
            },
          })
        }
      /> */}
    </div>
  )
}
