"use client"

import { Button, ButtonProps } from "antd"
import React from "react"
import Image from "next/image"

import { CometChat } from "@cometchat/chat-sdk-javascript"
import { chatUidCurrentState, isGoChatUidState } from "@/recoil/chat"
import { useSetRecoilState } from "recoil"
import { useRouter } from "@/i18n/routing"
import { useNotificationContext } from "@/component/Layout/NotificationContext"
import { useTranslations } from "next-intl"

interface IButtonProps extends ButtonProps {
  title: string
  icon?: string
  className?: string
  onClick: any
  type?: "link" | "text" | "default" | "primary" | "dashed"
  isLoading?: boolean
}

export const RenderMyContactStatus = (status: string, className?: string) => {
  const isOnline = status === "online"

  return (
    <div className={`flex items-center px-5 py-2.5 rounded-md ${className || ""}`}>
      <span className="relative mr-2">
        <span className={`w-4 h-4 rounded-full block opacity-[.32] ${isOnline ? "bg-[var(--success-90)]" : "bg-[var(--danger-70)]"}`}></span>
        <span className={`w-2 h-2 rounded-full absolute top-1 left-1 ${isOnline ? "bg-[var(--success-90)]" : "bg-[var(--danger-70)]"}`}></span>
      </span>
      <span className={`text-sm font-normal ${isOnline ? "text-[var(--success-90)]" : "text-[var(--danger-70)]"}`}>{isOnline ? "Online" : "Offline"}</span>
    </div>
  )
}

export const renderButton = (props: IButtonProps) => {
  return (
    <Button
      loading={props?.isLoading}
      type={props?.type}
      className={`w-full p-4 md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 xl:!h-16 !rounded-lg ${props?.className || ""}`}
      onClick={props?.onClick}>
      {props?.icon && (
        <Image
          src={props?.icon || ""}
          alt={props?.title}
          width={24}
          height={24}
        />
      )}
      {props?.title}
    </Button>
  )
}

export const useOpenChat = () => {
  const router = useRouter()
  const { notify } = useNotificationContext()
  const setIsGoChat = useSetRecoilState(isGoChatUidState)
  const setChatUser = useSetRecoilState(chatUidCurrentState)
  const transMessage = useTranslations("message")

  const openChat = async (uid: string, messageError?: string) => {
    try {
      const user = await CometChat.getUser(uid)
      if (user) {
        setChatUser(user)
        setIsGoChat(true)
        router.push("/chat")
      }
    } catch (error) {
      console.error("User not found", error)
      setIsGoChat(false)
      notify({
        type: "error",
        message: transMessage("something_wrong"),
        description: messageError || transMessage("user_not_exist_or_stop_used"),
      })
    }
  }

  return openChat
}
