import { useEffect, useState } from "react";
import { CometChatMessageComposer, CometChatMessageHeader, CometChatMessageList } from "@cometchat/chat-uikit-react";
import { ChatSelector } from "../ChatSelector";
import { useSelector } from "react-redux";
import { AppStore } from "@/lib/store";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import ChatCustomFetch from "@/Utils/APIRequest/ChatAxiosInstance";
import { ChatConversations, ChatGroup } from "@/Utils/APIRequest/Endpoints";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import PrimaryButton from "@/Component/Common/Forms/PrimaryButton";
import Link from "next/link";
import moment from "moment";
import { useRouter } from "next/navigation";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import { notifyCometChatRead } from "@/Utils/notifyCometChatRead";

const ChatMessages = () => {
    const router = useRouter()
    const chatUserData: any = useSelector((state: AppStore) => state.cometChatSlice.chatUserData);
    const userDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);
    const [groupState, setGroupState] = useState<any>(null);
    const [conversationState, setConversationState] = useState<any>(null)
    const [selectedGroup, setSelectedGroup] = useState<any>(null);
    const [listConversationState, setListConversationState] = useState<any>(null)
    const { translations } = useTranslation();

    const [selectedUser, setSelectedUser] = useState<CometChat.User | undefined>(undefined);
    const [selectedCall, setSelectedCall] = useState<CometChat.Call | undefined>(undefined);

    useEffect(() => {
        const fetchGroups = async () => {
            const groupRequest = await ChatCustomFetch({ url: ChatGroup }, null, false)
            if (groupRequest?.data) {
                setGroupState(groupRequest?.data)
                const getConversations = await ChatCustomFetch({ url: ChatConversations }, null, false)
                console.log("getConversations", getConversations);
                setConversationState(getConversations?.data)
            }
        };
        if (chatUserData) {
            fetchGroups();
        }
    }, [chatUserData]);

    const getLastMessageFromConversation = (groupData) => {
        let { conversationId } = groupData
        let obj = conversationState?.data?.find((conversation) => conversation?.conversationId == conversationId)
        let tempText = obj?.lastMessage?.data?.text?.length > 50 ? `${obj?.lastMessage?.data?.text?.substring(0, 50)} .....` : obj?.lastMessage?.data?.text
        return { text: tempText }
    }

    const notifyBrandRead = async (group) => {
        const guid = group?.guid;
        if (!guid) return;

        const conversation = conversationState?.data?.find((item) => item?.conversationId == group?.conversationId);
        const meta = group?.metadata || conversation?.conversationWith?.metadata || {};
        let campaignId = meta?.campaign_id || meta?.campaignId;
        let brandId = meta?.brand_id || meta?.brand?.id || meta?.users?.id;

        if (!campaignId || !brandId) {
            try {
                const cometGroup = await CometChat.getGroup(guid);
                const groupMeta = typeof cometGroup?.getMetadata === 'function' ? cometGroup.getMetadata() : {};
                campaignId = campaignId ;
                brandId = brandId;
            } catch (err) {
                console.error(err);
            }
        }

        if (!brandId) {
            try {
                const membersRequest = new CometChat.GroupMembersRequestBuilder(guid).setLimit(30).build();
                const members = await membersRequest.fetchNext();
                brandId = members
                    .map((member) => (typeof member.getUid === 'function' ? member.getUid() : member?.uid))
                    .find((uid) => uid && String(uid) !== String(userDetails?.id));
            } catch (err) {
                console.error(err);
            }
        }

        // Influencer is opening the chat — sender_id is the brand.
        notifyCometChatRead({ campaign_id: campaignId, sender_id: brandId });
    };

    const getListGroupConversations = async (group) => {
        setSelectedGroup(group)
        void notifyBrandRead(group);
        const getListConversations = await ChatCustomFetch({ url: `${ChatGroup}/${group?.guid}/messages` }, null, false)
        console.log("getListConversations", getListConversations);
        setListConversationState(getListConversations?.data?.data)
    }

    return chatUserData ? (
        <div className="conversations-with-messages grid grid-cols-12 gap-2">
            <div className="conversations-wrapper col-span-4">
                <div>
                    {groupState?.data?.length > 0 ?
                        groupState?.data?.map((group) => (
                            <div className={`${selectedGroup?.conversationId == group?.conversationId ? "bg-primary text-white" : ""} cursor-pointer p-2 hover:shadow-md flex gap-3`} key={group?.conversationId} onClick={() => getListGroupConversations(group)}>
                                <ImageWithFallback src={null} height={35} weight={35} className="rounded-full" alt={group?.name} />
                                <div className="flex flex-col">
                                    <span className="font-bold">{group?.name}</span>
                                    <span>{getLastMessageFromConversation(group)?.text ?? ""}</span>
                                </div>
                            </div>
                        ))
                        :
                        "No Group Found"
                    }
                </div>
                {/* <ChatSelector
                    items={groups}
                    onSelectorItemClicked={(activeItem) => {
                        setSelectedUser(undefined);
                        setSelectedGroup(activeItem as CometChat.Group);
                        setSelectedCall(undefined);
                    }} /> */}
            </div>
            {selectedGroup ? (
                <div className="messages-wrapper col-span-8 border">
                    {
                        listConversationState?.length > 0 ? listConversationState.map((message: any) => (
                            <div key={message.id} className=" flex items-start gap-2 mb-2.5">
                                <ImageWithFallback className="w-12 min-w-12 h-12 rounded-full" src={message?.data?.entities?.sender?.entity?.avatar} alt={message?.data?.entities?.sender?.entity?.name} width={48} height={48} />
                                <div className="flex flex-col gap-2.5 items-start">
                                    <div className="flex flex-col gap-0.5">
                                        <h5 className="text-lg font-medium">{message.category === "interactive" ? "System" : message?.data?.entities?.sender?.entity?.name}</h5>
                                        <span className="text-xs text-tertiary">{moment.unix(message.sentAt).format("hh:mm A")}</span>
                                    </div>

                                    {message.category === "interactive" ?
                                        <>
                                            <p>{message?.data?.text}</p>
                                            <div className="bg-gray/30 rounded-xl border-l-8 px-5 py-2.5 border-primary flex-col flex text-sm">
                                                <label>{translations?.jobOffer}</label>
                                                <span>{translations?.amount}: ${message?.data?.amount}</span>
                                                <span>{translations?.dueOn}: {message?.data?.due}</span>
                                                {message?.data?.link && <Link className="text-primary font-semibold underline text-sm mt-1.5" href={message?.data?.link}>View Job Details</Link>}
                                            </div>
                                            <PrimaryButton customClass={'min-w-40 !rounded-full !text-sm'} onClick={() => { router.push(message?.data?.link) }}>Accept Offer</PrimaryButton>
                                        </> :
                                        <p>{message?.data?.text}</p>
                                    }
                                </div>
                            </div>
                        ))
                            : <div className="p-2">Message to start the conversation</div>
                    }
                    {/* <CometChatMessageHeader user={selectedUser} group={selectedGroup} />
                    <CometChatMessageList user={selectedUser} group={selectedGroup} />
                    <CometChatMessageComposer user={selectedUser} group={selectedGroup} /> */}
                </div>
            ) : (
                <div className="empty-conversation col-span-8 border p-2">Select Conversation to start</div>
            )}
        </div>
    ) : undefined;
};

export default ChatMessages;