"use client";

import React, { useEffect, useRef, useState } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { MoreVertical, MessageSquarePlus, CircleDashed, Search, Loader2, Check, CheckCheck, Locate, MapPin, X, PhoneOutgoing, PictureInPicture, PictureInPicture2, LucidePictureInPicture } from "lucide-react";
import { useInfiniteConversationContacts, useLabel, useSearchMessages, useWhatsappProfile, useEditContact, useEditLabelContact } from "@/hooks/useWhatsApp";
import { useChatStore } from "@/store/useChatStore";
import { Contact, LabelContact } from "@/types/contacts";
import { useQueryClient } from '@tanstack/react-query';
import { useBranch, useSetting } from '@/hooks/useClientApp';
import { cn, fLimitation, parseMessage } from '@/lib/utils';
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from './ui/dropdown-menu';
import Link from 'next/link';
import { Branch } from '@/types/settings';
import { Skeleton } from './ui/skeleton';
import dynamic from 'next/dynamic';
import { Conversation } from '@/types/conversations';
import { Label } from '@radix-ui/react-label';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog';
import { Checkbox } from './ui/checkbox';



interface SidebarProps {
    onSelectContact?: () => void;
}

const Sidebar = ({ onSelectContact }: SidebarProps) => {
  
    const {
        data,
        dataUpdatedAt,
        isLoading,
        error,
        fetchNextPage,
        hasNextPage,
        isFetchingNextPage,
    } = useInfiniteConversationContacts();


    const contacts = data?.pages.flatMap(page => page.result) || [];
    const loadMoreRef = useRef<HTMLDivElement>(null);
    const queryClient = useQueryClient();

    const { selectedContact, setSelectedContact, setPaginationWindow, 
        selectedBranch, setSelectedBranch,setContactId,
        setSearchConversationContact,setLoadingFirstConversation, 
        selectedLabel, setSelectedLabel, setLightBoxImages, setMessageId,
        openMessageTemplate, setOpenMessageTemplate, setWithoutContact, searchConversationContact,
        setPageMessageId, filterUnreplied, setFilterUnreplied
    } = useChatStore();
    const { data: searchMessagesData, isLoading: isLoadingMessages } = useSearchMessages(searchConversationContact);
    const  { data: profileBussiness } = useWhatsappProfile();
    const { data: setting} = useSetting();
    const { data: branch } = useBranch();
    const { data: labels, isFetching: isFetchingLabel } = useLabel();

    const [pendingContact, setPendingContact] = useState<Contact | null>(null);
    const [modalBranchId, setModalBranchId] = useState<string>("");
    const [modalLabelIds, setModalLabelIds] = useState<number[]>([]);
    const [tempSelectedBranch, setTempSelectedBranch] = useState<number[]>(selectedBranch);

    useEffect(() => {
        setTempSelectedBranch(selectedBranch);
    }, [selectedBranch]);

    const editContactMutation = useEditContact();
    const editLabel = useEditLabelContact();

    const handleContactClick = (contact: Contact) => {
        if (!contact) return;
        const hasNoLabels = !contact.labels || contact.labels.length === 0;
        const isPusat = contact.branch_name === 'Pusat' || !contact.branch_name;

        if (isPusat || hasNoLabels) {
            setPendingContact(contact);
            setModalBranchId(contact.branch_id?.toString() || "");
            setModalLabelIds(contact.labels?.map(l => l.id) || []);
        }

        proceedWithContactClick(contact);
    };

    const proceedWithContactClick = (contact: Contact) => {
        setPaginationWindow(false);
        setLoadingFirstConversation(true);
        setLightBoxImages([]);
        setSelectedContact(contact);
        if (onSelectContact) {
            onSelectContact();
        }
    };

    const handleSaveModal = async () => {
        if (!pendingContact) return;
        
        try {
            let updatedBranchId = pendingContact.branch_id;
            let updatedBranchName = pendingContact.branch_name;

            if (modalBranchId && modalBranchId !== pendingContact.branch_id?.toString()) {
                const res = await editContactMutation.mutateAsync({
                    first_name: pendingContact.name,
                    last_name: pendingContact.last_name ?? '',
                    account_id: process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE ?? '',
                    branch: modalBranchId,
                    phone_number: pendingContact.phone_number,
                    contact_id: pendingContact.id.toString(),
                    province_id: pendingContact.province_id?.toString() ?? '',
                    city_id: pendingContact.city_id?.toString() ?? '',
                    address: pendingContact.address ?? ''
                });
                updatedBranchId = res.data.branch_id;
                updatedBranchName = branch?.find(b => b.id.toString() === modalBranchId)?.name || 'Pusat';
            }

            if (modalLabelIds.length > 0) {
                await editLabel.mutateAsync({
                    contact_id: pendingContact.id.toString(),
                    label_id: modalLabelIds.join(',')
                });
            }
            
            const updatedContact = {
                ...pendingContact, 
                branch_id: Number(updatedBranchId),
                branch_name: updatedBranchName,
                labels: labels?.filter((l: LabelContact) => modalLabelIds.includes(l.id)) as any
            } as Contact;
            
            setPendingContact(null);
            proceedWithContactClick(updatedContact);
        } catch(err) {
            console.error(err);
        }
    };

    const handlePageMessageId = (message: Conversation, contact: Contact) => {
        proceedWithContactClick(contact);
        setPageMessageId(message.id);
        queryClient.invalidateQueries({queryKey:['page-message']});
        
        setTimeout(() => {
            window.location.hash = `#${message.id.toString()}`;
        }, 300);
    };



    // Infinite scroll handler using Intersection Observer
    useEffect(() => {
        const loadMoreElement = loadMoreRef.current;
        if (!loadMoreElement || !hasNextPage || isFetchingNextPage) return;

        // Find the ScrollArea viewport element
        const scrollAreaViewport = loadMoreElement.closest('[data-slot="scroll-area"]')?.querySelector('[data-slot="scroll-area-viewport"]') as HTMLElement | null;

        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting) {
                    fetchNextPage();
                }
            },
            {
                root: scrollAreaViewport || null,
                rootMargin: '100px',
                threshold: 0.1,
            }
        );

        observer.observe(loadMoreElement);

        return () => {
            observer.disconnect();
        };
    }, [hasNextPage, isFetchingNextPage, fetchNextPage, contacts.length]);

    return (
        <>
        <div className="w-full md:max-w-[400px] h-full flex flex-col border-r border-gray-200 dark:border-gray-800 bg-white dark:bg-[#111b21]">
            {/* Header */}
            <div className="h-16 px-4 flex items-center justify-between bg-[#f0f2f5] dark:bg-[#202c33] shrink-0">
                <div className="flex flex-row gap-2 items-center">
                    <Avatar className="cursor-pointer">
                        <AvatarImage src={ profileBussiness?.profile_pic_url } />
                        <AvatarFallback  className="bg-gray-300 dark:bg-zinc-800">{profileBussiness?.business_name[0]}</AvatarFallback>
                    </Avatar>
                    <div className="flex flex-col">
                        <span className="text-sm font-semibold">{profileBussiness?.business_name}</span>
                        <span className="text-xs text-gray-500 dark:text-gray-400">{profileBussiness?.phone_number}</span>
                       
                    </div>
                </div>
             
                <div className="flex items-center gap-2">
                    <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400" onClick={() => {
                        setOpenMessageTemplate(true);
                        setWithoutContact(true);
                    }}>
                        <MessageSquarePlus className="h-5 w-5" />
                    </Button>
                    {/* <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                        <MoreVertical className="h-5 w-5" />
                    </Button> */}
                </div>
            </div>

            {/* Search */}
            <div className="p-2 bg-white dark:bg-[#111b21] shrink-0 flex flex-col gap-2">
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Link href={"#"} className="text-sm text-emerald-600 dark:text-emerald-400">
                            <div className="flex flex-row flex-wrap items-center font-semibold gap-1">
                                <MapPin className="h3 w-3"/>
                                <span>{branch?.filter(item => selectedBranch.includes(item.id) && item.is_access).map(item => item.name).join(', ')}</span>
                            </div>
                            
                        </Link>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent className="w-56 p-2">
                        {
                            branch?.map((item:Branch, index:number) => (
                                <div key={index} className="flex items-center space-x-2 py-1.5 px-2">
                                    <Checkbox
                                        id={`branch-${item.id}`}
                                        checked={tempSelectedBranch.includes(item.id) && item.is_access}
                                        disabled={!item.is_access}
                                        onCheckedChange={(e) => {
                                            let newSelectedBranch;
                                            if (e) {
                                                newSelectedBranch = [...tempSelectedBranch, item.id];
                                            } else {
                                                newSelectedBranch = tempSelectedBranch.filter((id) => id !== item.id);
                                            }
                                            if (!newSelectedBranch || newSelectedBranch.length === 0) {
                                                newSelectedBranch = [1];
                                            }
                                            setTempSelectedBranch(newSelectedBranch);
                                        }}
                                    />
                                    <label htmlFor={`branch-${item.id}`} className={`text-sm font-medium leading-none ${!item.is_access ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}>
                                        {item.name}
                                    </label>
                                </div>
                            ))
                        }
                        <div className="pt-2 mt-1 border-t">
                            <Button size="sm" className="w-full" onClick={() => setSelectedBranch(tempSelectedBranch)}>
                                Filter
                            </Button>
                        </div>
                    </DropdownMenuContent>
                </DropdownMenu>
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500 dark:text-gray-400" />
                    <Input
                        name="search"
                        placeholder="Cari..."
                        onChange={(e) => setSearchConversationContact(e.currentTarget.value)}
                        className="pl-10 bg-[#f0f2f5] dark:bg-[#202c33] border-none focus-visible:ring-0 h-9"
                    />
                   
                </div>
                 <span
                    onClick={(e) => {
                        setFilterUnreplied(!filterUnreplied)
                    }}
                    className={cn(filterUnreplied ? "border border-gray-800 dark:border-zinc-300 text-teal-800 bg-teal-100 dark:text-teal-100 dark:bg-teal-900" : "bg-gray-200 text-gray-800 dark:text-gray-200 dark:bg-gray-700", "h-5 cursor-pointer")}
                    style={{
                        padding: "2px 6px",
                        borderRadius: "4px",
                        fontSize:'10px',
                        display: "inline-flex",
                        alignItems: "center",
                        gap: "4px",
                        whiteSpace: 'nowrap'
                    }}
                >
                    <div className="w-1.5 h-1.5 rounded-full bg-green-700"></div>
                    Belum Dibalas
                </span>
                {
                    isFetchingLabel ? 
                        <Skeleton className="w-full h-5"/>
                    :
                    <div className="flex h-10 overflow-x-auto overflow-y-hidden gap-1 scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-700 py-1"
                        style={{ WebkitOverflowScrolling: "touch" }}>
                            <span
                                onClick={(e) => {
                                    setSelectedLabel(0)
                                }}
                                className={cn(selectedLabel == 0 ? "border border-gray-800 dark:border-zinc-300" : "", "h-5 cursor-pointer bg-gray-200 dark:bg-gray-700")}
                                style={{
                                    padding: "2px 6px",
                                    borderRadius: "4px",
                                    fontSize:'10px',
                                    display: "inline-block",
                                    whiteSpace: 'nowrap'
                                }}
                            >
                                Semua
                            </span>
                            
                           

                        {labels?.map((item:LabelContact, index:number) => (
                            <span
                                onClick={(e) => {
                                    setSelectedLabel(item.id);
                                }}
                                key={index}
                                className={cn(selectedLabel == item.id ? "border border-gray-800 dark:border-zinc-300" : "","h-5 cursor-pointer")}
                                style={{
                                    backgroundColor: item.color,
                                    color: item.text_color ?? "#fff",
                                    padding: "2px 6px",
                                    borderRadius: "4px",
                                    fontSize:'10px',
                                    display: "inline-block",
                                    whiteSpace: 'nowrap'
                                }}
                            >
                                {item.name}
                            </span>
                        ))}
                    </div>
                }
               
            </div>

            {/* Chat List */}
            <ScrollArea className="flex-1 h-0 ">
                    {isLoading ? (
                        <div className="flex items-center justify-center h-32">
                            <Loader2 className="h-6 w-6 animate-spin text-gray-500" />
                        </div>
                    ) : error ? (
                        <div className="flex items-center justify-center h-32">
                            <p className="text-sm text-red-500">Failed to load contacts</p>
                        </div>
                    ) : contacts.length === 0 ? (
                        <div className="flex items-center justify-center h-32">
                            <p className="text-sm text-gray-500">No contacts found</p>
                        </div>
                    ) : (
                        <>
                            {/* Chats Section */}
                            {searchConversationContact && contacts.length > 0 && (
                                <div className="px-4 py-2 text-xs font-bold text-teal-600 uppercase bg-white dark:bg-[#111b21]">Chats</div>
                            )}
                            {contacts.map((contact, index) => (
                                <div
                                    key={index}
                                    onClick={() => handleContactClick(contact)}
                                    className={`flex items-center gap-3 p-3 cursor-pointer hover:bg-[#f5f6f6] dark:hover:bg-[#202c33] transition-colors border-b border-gray-100 dark:border-gray-800 last:border-0 ${
                                        selectedContact?.id === contact.id ? 'bg-[#f0f2f5] dark:bg-[#2a3942]' : ''
                                    }`}
                                >
                                    <div className="flex-1 overflow-hidden pl-2">
                                        <div className="flex justify-between items-center">
                                            <h3 className="font-medium text-gray-900 dark:text-gray-100">{contact.name} {contact.last_name}</h3>
                                            <div className="flex flex-row">
                                            {contact.current_conversation?.last_message_at && (
                                                <span className="text-xs text-gray-500 dark:text-gray-400 shrink-0 mr-1">
                                                    {
                                                        (() => {
                                                            const msgDate = new Date(contact.current_conversation.last_message_at);
                                                            const now = new Date();
                                                            const isToday = msgDate.getDate() === now.getDate() &&
                                                                            msgDate.getMonth() === now.getMonth() &&
                                                                            msgDate.getFullYear() === now.getFullYear();
                                                            return isToday 
                                                                ? msgDate.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) 
                                                                : msgDate.toLocaleDateString();
                                                        })()
                                                    }
                                                </span>
                                            )}
                                            <div className={`flex items-center gap-1`}>
                                                {contact?.current_conversation?.last_messages?.direction == "outbound" && (
                                                    <span className={cn("text-[10px]", status === 'read' ? "text-blue-500" : "text-gray-500")}>
                                                        {/* Simple checkmark svg */}
                                                        {contact?.current_conversation?.last_messages.status == 'sent' && <Check className='h-3 w-3 text-gray'/> }
                                                        {contact?.current_conversation?.last_messages.status == 'delivered' && <CheckCheck className='h-3 w-3 text-gray'/> }
                                                        {contact?.current_conversation?.last_messages.status == 'read' && <CheckCheck className='h-3 w-3 text-green-500'/> }
                                                        {contact?.current_conversation?.last_messages.status == 'failed' && <X className='h-3 w-3 text-red-500'/> }

                                                    </span>
                                                )}
                                            </div>
                                            </div>
                                        </div>
                                        <div className="flex justify-between items-center">
                                            <div className={cn("flex flex-row justify-between items-center gap-x-2 gap-y-1 pr-2 w-full")}>
                                                {
                                                    contact.current_conversation?.last_message 
                                                    ? (
                                                        contact?.current_conversation?.last_messages.message_type == "template" ?
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}>
                                                            {contact?.current_conversation?.last_messages.direction == "outbound" && (
                                                                <span className="font-semibold text-sm">{contact?.current_conversation?.last_messages?.maded_by_json?.name} :</span>
                                                            )} 
                                                        <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(contact?.current_conversation?.last_messages?.message_json.filter((fill:any) => fill.type == 'body').at(0).text),0, 80)}}/>
                                                        </span>
                                                        :
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}>
                                                        {contact?.current_conversation?.last_messages.direction == "outbound" && (
                                                                <span className="font-semibold text-sm">{contact?.current_conversation?.last_messages?.maded_by_json?.name} :</span>
                                                        )} <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(contact.current_conversation.last_message),0, 80)}}/>
                                                        </span>
                                                    )
                                                    :  contact.current_conversation?.last_messages?.message_type == "image" ? (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}>
                                                            Photo
                                                        </span>
                                                    ) :  contact.current_conversation?.last_messages?.message_type == "video" ? (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}> 
                                                            Video
                                                        </span>
                                                    ) :  contact.current_conversation?.last_messages?.message_type == "sticker" ? (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}> 
                                                            Reaction
                                                        </span>
                                                    ) :  contact.current_conversation?.last_messages?.message_type == "document" ? (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}> 
                                                            Document
                                                        </span>
                                                    )
                                                    :  contact.current_conversation?.last_messages?.message_type == "audio" ? (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}> 
                                                            Audio
                                                        </span>
                                                    )
                                                    : (
                                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full", contact?.current_conversation?.last_messages?.direction == "inbound"  && "text-green-700")}>
                                                            No messages yet
                                                        </span>
                                                    )
                                                }
                                            
                                            </div>
                                            {/* {contact.message_count && contact.message_count > 0 && (
                                                <span className="bg-[#25d366] text-white text-[10px] font-bold h-5 min-w-5 px-1 flex items-center justify-center rounded-full shrink-0">
                                                    {contact.message_count > 99 ? '99+' : contact.message_count}
                                                </span>
                                            )} */}
                                            {
                                                contact?.current_conversation?.last_messages.direction == "inbound" && (
                                                    <div className="w-3 h-3 rounded-full bg-green-700"></div>
                                                )
                                            }
                                        </div>
                                        <div className="flex flex-row justify-between items-center">
                                            {contact.labels && (
                                                <div className="flex flex-wrap flex-row gap-1 mt-1">
                                                    {contact.labels.map((item, index:number) => (
                                                        <span
                                                            key={index}
                                                            style={{
                                                                backgroundColor: item.color,
                                                                color: item.text_color ?? "#fff",
                                                                padding: "2px 6px",
                                                                borderRadius: "4px",
                                                                fontSize:'10px',
                                                                display: "inline-block",
                                                            }}
                                                        >
                                                            {item.name}
                                                        </span>
                                                    ))}
                                                </div>
                                            )}
                                            <div className="flex flex-row">
                                                 {
                                                    (contact?.city?.name) && (
                                                        <span className="text-[10px] px-1 rounded-md text-gray-500 dark:text-gray-400">{contact?.city?.name}</span>
                                                    )
                                                }
                                                <span className={cn(`text-[10px] border px-1 rounded-md  h-[18px] text-white bg-gray-500`)} style={{backgroundColor:contact?.branch_bg_color ?? '#666666'}}>{contact?.branch_alias ?? contact?.branch_name}</span>
                                            </div>
                                        </div>
                                        
                                    </div>
                                </div>
                            ))}
                            {/* Sentinel element for infinite scroll */}
                            {hasNextPage && (
                                <div ref={loadMoreRef} className="h-1" />
                            )}
                            {isFetchingNextPage && (
                                <div className="flex items-center justify-center py-4">
                                    <Loader2 className="h-5 w-5 animate-spin text-gray-500" />
                                </div>
                            )}
                        </>
                    )}
                    {/* Messages Section - Only show when searching */}
                    {searchConversationContact && searchMessagesData?.result && searchMessagesData.result.length > 0 && (
                        <>
                            <div className="px-4 py-2 text-xs font-bold text-teal-600 uppercase bg-white dark:bg-[#111b21]">Messages</div>
                            {searchMessagesData.result.map((msg, index) => (
                                <div
                                    key={`msg-${index}`}
                                    onClick={() => {
                                        const minimalContact = msg.contacts || {
                                            id: msg.contact_id,
                                            name: msg.contacts_name,
                                            last_name: msg.contacts_last_name,
                                            phone_number: msg.contacts_phone_number,
                                            labels: [],
                                            branch_name: '',
                                            branch_id: 1,
                                            is_available: true
                                        };
                                        handlePageMessageId(msg, minimalContact as Contact);
                                    }}
                                    className="flex items-start gap-3 p-3 max-w-[400px] cursor-pointer hover:bg-[#f5f6f6] dark:hover:bg-[#202c33] transition-colors border-b border-gray-100 dark:border-gray-800 last:border-0"
                                >
                                    <div className="flex-1 overflow-hidden ">
                                        <div className="flex justify-between items-center mb-1">
                                            <h3 className="font-medium text-gray-900 dark:text-gray-100">{msg.contacts_name} {msg.contacts_last_name}</h3>
                                            <span className="text-xs text-gray-500 dark:text-gray-400">
                                                {new Date(msg.created_at_date.original).toLocaleDateString()}
                                            </span>
                                        </div>
                                        <div className="text-sm text-gray-600 dark:text-gray-400 truncate flex flex-col ">
                                            <span className="text-xs text-gray-400 mb-1">{msg.contacts_phone_number}</span>
                                                    {msg?.message_type == "template" ?
                                                        <span className="text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full">
                                                            {msg?.direction == "outbound" && (
                                                                <span className="font-semibold text-sm">{msg?.maded_by_json?.name} :</span>
                                                            )} 
                                                        <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(msg?.message_json.filter((fill:any) => fill.type == 'body').at(0).text),0, 80)}}/>
                                                        </span>
                                                    :  msg?.message_type == "image" ? (
                                                        <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                            Photo
                                                        </span>
                                                    ) :  msg?.message_type == "video" ? (
                                                        <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                            Video
                                                        </span>
                                                    ) :  msg?.message_type == "sticker" ? (
                                                        <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                            Reaction
                                                        </span>
                                                    ) :  msg?.message_type == "document" ? (
                                                        <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                            Document
                                                        </span>
                                                    )
                                                    :  msg?.message_type == "audio" ? (
                                                        <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                            Audio
                                                        </span>
                                                    ) : 
                                                        <span className="text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full">
                                                            {msg?.direction == "outbound" && (
                                                                <span className="font-semibold text-sm">{msg?.maded_by_json?.name} :</span>
                                                            )} <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(msg?.message_text),0, 80)}}/>
                                                        </span>
                                                    }
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </>
                    )}
            </ScrollArea>
        </div>
        
            {/* Modal Enforcement */}
            <Dialog open={!!pendingContact} onOpenChange={(open) => { if (!open) setPendingContact(null) }}>
                <DialogContent className="max-w-xl">
                    <DialogHeader>
                        <DialogTitle>Lokasi Cabang</DialogTitle>
                    </DialogHeader>
                    
                    {
                        modalBranchId == '1' && (
                               <div className="bg-amber-50 dark:bg-amber-950/50 border border-amber-200 dark:border-amber-800/50 text-amber-800 dark:text-amber-400 p-3 rounded-md text-sm mb-4">
                                Tentukan lokasi cabang dan set Label PIC.
                            </div>
                        )
                    }
                 

                    <div className="flex flex-row flex-wrap gap-4 mb-4">
                        {branch?.map((b) => (
                            <label key={b.id} className="flex items-center gap-2 cursor-pointer">
                                <input 
                                    type="radio" 
                                    name="branch" 
                                    value={b.id.toString()}
                                    checked={modalBranchId === b.id.toString()}
                                    onChange={(e) => setModalBranchId(e.target.value)}
                                    className="w-4 h-4 text-teal-600 border-gray-300 focus:ring-teal-500"
                                />
                                <span className="text-sm font-medium">{b.name}</span>
                            </label>
                        ))}
                    </div>

                    <DialogTitle className="mt-4">Label</DialogTitle>
                    <div className="flex flex-col flex-wrap gap-2 mb-5 max-h-48 overflow-auto">
                        {labels?.map((label: LabelContact) => (
                            <div key={label.id} className="flex items-center gap-2">
                                <Checkbox 
                                    id={`label-${label.id}`} 
                                    checked={modalLabelIds.includes(label.id)}
                                    onCheckedChange={(checked) => {
                                        if (checked) {
                                            setModalLabelIds(prev => [...prev, label.id]);
                                        } else {
                                            setModalLabelIds(prev => prev.filter(id => id !== label.id));
                                        }
                                    }}
                                />
                                <label htmlFor={`label-${label.id}`} className="cursor-pointer text-sm" style={{
                                    backgroundColor: label.color,
                                    color: label.text_color ?? "#fff",
                                    padding: "2px 6px",
                                    borderRadius: "4px",
                                }}>
                                    {label.name}
                                </label>
                            </div>
                        ))}
                    </div>

                    <DialogFooter className="mt-6">
                        <Button variant="outline" onClick={() => setPendingContact(null)} disabled={editContactMutation.isPending || editLabel.isPending}>Close</Button>
                        <Button 
                            onClick={handleSaveModal} 
                            disabled={!modalBranchId || modalBranchId === branch?.find(b => b.name === 'Pusat')?.id?.toString() || modalLabelIds.length === 0 || editContactMutation.isPending || editLabel.isPending}
                        >
                            {(editContactMutation.isPending || editLabel.isPending) ? <Loader2 className="h-4 w-4 animate-spin mr-2"/> : null}
                            Simpan
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

        </>
    );
};

export default Sidebar;

