"use client";

import React, { useState, useEffect, useRef } 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, Search, Paperclip, Smile, Mic, Send, Loader2, Plus, Image as ImageIcon, FileText, Film, X, PictureInPicture, ImagePlusIcon, VideoOffIcon, Video, BookTemplate, LayoutPanelTop, TagIcon, Phone, ArrowLeft, UserCheck, Trophy } from "lucide-react";
import MessageBubble from './message-bubble';
import { EmojiClickData, EmojiStyle } from 'emoji-picker-react';
import dynamic from "next/dynamic";
import { useChatStore } from "@/store/useChatStore";
import { useContactInfo, useContactDetail, useEditContact, useEditLabelContact,usePageMessage, useInfiniteConversations, useLabel, useSendMessage } from "@/hooks/useWhatsApp";
import { Textarea } from './ui/textarea';
import { useAuth } from '@/contexts/auth-context';
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from './ui/dropdown-menu';
import { Drawer, DrawerTrigger } from './ui/drawer';
import MessageInputTemplate from './message-input-template';
import MarketingKitTextDialog from './marketing-kit-text-dialog';
import MarketingKitBannerDialog from './marketing-kit-banner-dialog';
import { ImageReply, TemplatetReply, TextReply } from './message-reply';
import { Checkbox } from "@/components/ui/checkbox"
// import plugins if you need
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';
import { SlideImage } from 'yet-another-react-lightbox';
import { useBranch, useSetting } from '@/hooks/useClientApp';
import { Branch } from '@/types/settings';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from './ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel } from './ui/form';
import { ContactLabel, LabelContact } from '@/types/contacts';
import { Label } from './ui/label';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useForm } from 'react-hook-form';
import VoiceCall from './voice-call';
import { cn, fLimitation, fToNow, parseMessage } from '@/lib/utils';
import { fa } from 'zod/v4/locales';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { usePathname } from 'next/navigation';
import ContactEdit from './contact-edit';
import ChatStatisticsModal from './chat-statistics-modal';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';

const EmojiPicker = dynamic(
    () => import('emoji-picker-react').then((mod: any) => mod.default),
    { ssr: false }
) as any;

interface ChatWindowProps {
    onBack?: () => void;
}

const ChatWindow = ({ onBack }: ChatWindowProps) => {
    const { selectedContact, paginationWindow, setPaginationWindow, setConversations,lightBoxImages, 
        setLightBoxImages, messageReply, setMessageReply, contactId,
        setPageSelectedMessage,
        openMessageTemplate, setOpenMessageTemplate, setWithoutContact,setLoadingFirstConversation,loadingFirstConversation,
        draftMessages, setDraftMessage
     } = useChatStore();
    const { data: branch } = useBranch();
    const { data:labels} = useLabel();
    const [newMessage, setNewMessage] = useState("");
    useEffect(() => {
        if (selectedContact?.id) {
            setNewMessage(draftMessages[selectedContact.id.toString()] || "");
        } else {
            setNewMessage("");
        }
    }, [selectedContact?.id]);
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [attachmentFile, setAttachmentFile] = useState<File | null>(null);
    const [attachmentType, setAttachmentType] = useState<'image' | 'video' | 'document' | null>(null);
    const [attachmentPreview, setAttachmentPreview] = useState<string | null>(null);
    const [openDropDownMessage, setOpenDropDownMessage] = useState<boolean>(false);
    const [openMarketingKitText, setOpenMarketingKitText] = useState(false);
    const [openMarketingKitBanner, setOpenMarketingKitBanner] = useState(false);
    const scrollAreaRef = useRef<HTMLDivElement>(null);
    const isLoadingMoreRef = useRef<boolean>(false);
    const isLoadingMoreRefPrevious = useRef<boolean>(false);
    const addMessageMutation = useSendMessage();

    const handleCustomerClick = (e: React.MouseEvent, phone: string) => {
        e.stopPropagation();
        const baseUrl = process.env.NEXT_PUBLIC_LOGIN_URL?.replace('/login', '') || 'https://rumapedia.in';
        let formatted = phone;
        window.open(`${baseUrl}/admin/prospek/customer?search=${formatted}`, '_blank');
    };

    const { user } = useAuth();
    const editContactMutation = useEditContact();
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isProfileModalOpen, setIsProfileModalOpen] = useState(false);
    const [isChatStatisticsModalOpen, setIsChatStatisticsModalOpen] = useState(false);
    const [showVoiceCall, setShowVoiceCall] = useState(false);
    const [isSearchOpen, setIsSearchOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");
    const searchInputRef = useRef<HTMLInputElement | null>(null);
    const formLabel = useForm();
    const editLabel = useEditLabelContact();
    const { data: setting } = useSetting();
    const [heighInput, setHightInput] = useState<string>("auto");
    const refTextArea = useRef<HTMLTextAreaElement | null>(null);
    const { data: contactInfo, isLoading: isContactInfoLoading, isFetching: isFetchingContactInfo, refetch: refetchContactInfo } = useContactInfo(selectedContact?.id?.toString(), isProfileModalOpen || isChatStatisticsModalOpen);
    
    const {
        data,
        dataUpdatedAt,
        isLoading,
        error,
        refetch,
        fetchNextPage,
        fetchPreviousPage,
        hasNextPage,
        hasPreviousPage,
        isFetchingNextPage,
        isFetchingPreviousPage
    } = useInfiniteConversations();

    const {data: pageMessage, isFetching: isFetchingPageMessage} = usePageMessage();
   
    useEffect(() => {
        if(pageMessage?.page) {
            setPageSelectedMessage(pageMessage?.page);
        }
    },[isFetchingPageMessage])


    const pathname = usePathname()
        
    useEffect(() => {
        const hash = window.location.hash
        if (!hash) return
        setTimeout(() => {
            const el = document.getElementById(hash.replace('#', ''))
            if (!el) return
            el.scrollIntoView({ behavior: 'smooth' })
            el.focus({ preventScroll: true })
        }, 500)
    }, [pathname, isLoading, isFetchingPageMessage])
    

    const conversations = data?.pages.toReversed().flatMap(page => page.result) || [];
    const filteredConversations = searchQuery.trim().length > 0
        ? conversations.filter((conversation) => {
            const text = (conversation.message_text || "").toLowerCase();
            return text.includes(searchQuery.toLowerCase());
        })
        : conversations;


    const images: SlideImage[] = [];
    conversations.filter((messages) => messages.message_type === 'image' || messages.message_type === 'sticker' || messages.message_type === 'template')
    .map((messages) => {
        if(messages?.media_url) {
            images.push({
                src: messages?.media_url
            })
        }
        if(messages?.message_json?.filter((fill:any) => fill.type == 'header' && fill.format == 'image').at(0)?.text){
            images.push({
                src: messages?.message_json?.filter((fill:any) => fill.type == 'header' && fill.format == 'image').at(0)?.text
            })
        }
       
    })
    .filter((filter) => filter);


    useEffect(() => {
        if(!isLoading || !isFetchingNextPage) {
            setLightBoxImages(images);
        }
    },[dataUpdatedAt]);

    useEffect(() => {
        if(selectedContact) {
            formLabel.reset({
                label: selectedContact?.labels.map(label => label.id) || []
            })
        }
    },[selectedContact]);
    
    useEffect(() => {
        const viewport = scrollAreaRef.current;
        // Only scroll to bottom if contact actually changed and data is loaded
        if (viewport &&  !isLoading && !isLoadingMoreRef.current && !paginationWindow) {
            // Use a small delay to ensure DOM is updated
            viewport.scrollTop = viewport.scrollHeight;
            if (refTextArea.current) {
                refTextArea.current.focus()
            }
            setPaginationWindow(true);
            setLoadingFirstConversation(false);
        }
        
        
    }, [selectedContact?.id, conversations,contactId, isLoading]); // Only depend on contact ID, not conversations.length

    useEffect(() => {
        if (isSearchOpen && searchInputRef.current) {
            searchInputRef.current.focus();
        }
    }, [isSearchOpen]);

    useEffect(() => {
        if (messageReply && refTextArea.current) {
            setTimeout(() => {
                refTextArea.current?.focus();
            }, 100);
        }
    }, [messageReply]);

    const handleScroll = async () => {
        const viewport = scrollAreaRef.current;
        if (viewport?.scrollTop === 0) {
            const prevHeight = viewport.clientHeight;
            const prevScrollHight = viewport.scrollHeight;
            if(data?.pages.at(0)?.meta?.current_page != data?.pages.at(0)?.meta?.last_page) {
                isLoadingMoreRef.current = true;
                setPaginationWindow(true)
                fetchNextPage().then((res) => {
                    isLoadingMoreRef.current = false;
                    if((res.data?.pageParams.length ?? 0) > (data?.pageParams.length ?? 0)) {
                        viewport.scrollTop = prevScrollHight / (data?.pageParams.length || 0)
                    }
                });
              
            }
        } else {
            if(!isFetchingPreviousPage) {   
                    
                if(Math.ceil((viewport?.scrollTop ?? 0) + (viewport?.clientHeight ?? 0)) == viewport?.scrollHeight) {
                    if((data?.pages.at(0)?.meta?.current_page ?? 1) > 1) {
                        isLoadingMoreRefPrevious.current = true;
                        fetchPreviousPage().then((res) => {
                            isLoadingMoreRefPrevious.current = false;
                        });
                    }
                }
            }   
        }
      };



    const onEmojiClick = (emojiData: EmojiClickData) => {
        setNewMessage((prev) => {
            const next = prev + emojiData.emoji;
            if (selectedContact?.id) {
                setDraftMessage(selectedContact.id.toString(), next);
            }
            return next;
        });
    };

    useEffect(() => {
        return () => {
            if (attachmentPreview) {
                URL.revokeObjectURL(attachmentPreview);
            }
        };
    }, [attachmentPreview]);

    const resetComposer = () => {
        setNewMessage("");
        if (selectedContact?.id) {
            setDraftMessage(selectedContact.id.toString(), "");
        }
        setAttachmentFile(null);
        setAttachmentType(null);
        setMessageReply(null);
        if (refTextArea.current) {
            refTextArea.current.style.height = "2.25rem";
        }
        if (attachmentPreview) {
            URL.revokeObjectURL(attachmentPreview);
            setAttachmentPreview(null);
        }
    };

    const handleFileChange = (type: 'image' | 'video' | 'document', dropdown?:boolean | undefined) => (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        setAttachmentFile(file);
        setAttachmentType(type);
        if (type !== 'document') {
            const previewUrl = URL.createObjectURL(file);
            setAttachmentPreview(previewUrl);
        } else {
            setAttachmentPreview(null);
        }
        // Reset input so same file can be re-selected
        e.target.value = '';
        if(dropdown == true) setOpenDropDownMessage(!openDropDownMessage)
    };

    const buildPayload = () => {
        const accountId = process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE ?? '';
        const phoneNumber = selectedContact?.phone_number ?? '';
        const madedBy = JSON.stringify(user);

        
        if (attachmentFile && attachmentType) {
            const formData = new FormData();
            const fieldName = attachmentType === 'document' ? 'document' : attachmentType;

            formData.append('type', attachmentType);
            formData.append('account_id', accountId);
            formData.append('phone_number', phoneNumber);
            formData.append('maded_by', madedBy);
            formData.append('message', newMessage);
            formData.append(fieldName, attachmentFile);
            formData.append('filename', attachmentFile.name);

            return formData;
        }

        const payload: any = {
            type: 'text',
            account_id: accountId,
            message: newMessage,
            phone_number: phoneNumber,
            maded_by: JSON.stringify(user)
        }
        if(messageReply) payload.ref_message_id = messageReply?.message_id
        return payload;
    };

    const handleSendMessage = () => {
        if (!newMessage.trim() && !attachmentFile) return;

        const payload = buildPayload();

        addMessageMutation.mutateAsync(payload).then(() => {
            resetComposer();
        });
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };
    // Show empty state when no contact is selected
    if (!selectedContact) {
        return (
            <div className="flex-1 flex flex-col h-full bg-[#efeae2] dark:bg-[#0b141a] items-center justify-center">
                <div className="text-center">
                    <h3 className="text-xl font-medium text-gray-900 dark:text-gray-100 mb-2">
                        WhatsApp {setting?.name}
                    </h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                        Select a chat to start
                    </p>
                </div>
            </div>
        );
    }

   
    const onSubmitLabel = async (values:any) => {
        await editLabel.mutateAsync({
            contact_id:selectedContact?.id.toString() ?? '',
            label_id:values.label.join(',')
        }).then(() => {
            setIsDialogOpen(false);
        })
    }
   
    return (
        <div className="flex-1 flex flex-col h-full bg-[#efeae2] dark:bg-[#0b141a] relative" 
        onDragOver={e => {
            e.preventDefault();
            e.stopPropagation();
            e.dataTransfer.dropEffect = 'copy';
        }}
        onDrop={e => {
            e.preventDefault();
            e.stopPropagation();
            if (!selectedContact?.is_available || addMessageMutation.isPending) return;
        
            const files = Array.from(e.dataTransfer.files);
            if (files.length === 0) return;
        
            const file = files[0];
            // Check type and trigger corresponding handler
            if (file.type.startsWith("image/")) {
                handleFileChange('image')({ target: { files: [file] } } as any);
            } else if (file.type.startsWith("video/")) {
                handleFileChange('video')({ target: { files: [file] } } as any);
            } else if (
                file.type === "application/pdf" ||
                file.type.startsWith("application/") ||
                file.type.startsWith("text/") ||
                file.name.match(/\.(docx?|xlsx?|pptx?|txt|zip|rar|csv)$/i)
            ) {
                handleFileChange('document')({ target: { files: [file] } } as any);
            }
        }}
        title="Drag and drop a file here to attach">
            {/* Background Pattern Overlay - Light Mode */}
            <div className="absolute inset-0 opacity-40 dark:opacity-0 pointer-events-none bg-[url('/whatsapp-bg-light.png')] bg-repeat"></div>
            {/* Background Pattern Overlay - Dark Mode */}
            <div className="absolute inset-0 opacity-10">
                <div className="absolute inset-0 opacity-0 dark:opacity-100 pointer-events-none bg-[url('/wa-bg-dark.png')] bg-repeat"></div>
            </div>
            {
                selectedContact?.calling_permission == 'accept' && (selectedContact?.calling_expired == null || new Date(selectedContact?.calling_expired).getTime() > new Date().getTime())
                && (
                    <>
                        {showVoiceCall  && (
                            <VoiceCall
                                contactName={selectedContact?.name}
                                contactPhone={selectedContact?.phone_number}
                                contactAvatar={selectedContact?.profile_pic_url || undefined}
                                isIncoming={false}
                                onEndCall={() => setShowVoiceCall(false)}
                                onDecline={() => setShowVoiceCall(false)}
                            />
                        )}
                    </>
                )
            }
            
            {/* Header Dekstop */}
            <div className="h-16 px-4  hidden md:flex  items-center justify-between bg-[#f0f2f5] dark:bg-[#202c33] shrink-0 z-10 border-l border-gray-200 dark:border-gray-800">
                <div className="flex items-center gap-3 cursor-pointer" onClick={() => setIsProfileModalOpen(true)}>
                    <Avatar>
                        <AvatarImage src={selectedContact.profile_pic_url || undefined} />
                        <AvatarFallback>{selectedContact.name[0]?.toUpperCase() || 'U'}</AvatarFallback>
                    </Avatar>
                    <div>
                        <div className="flex items-center gap-2">
                            <h3 className="font-medium text-gray-900 dark:text-gray-100">{selectedContact.name}</h3>
                            {selectedContact.is_customer && (
                                <TooltipProvider>
                                    <Tooltip>
                                        <TooltipTrigger asChild>
                                            <div 
                                                className="text-emerald-500 hover:text-emerald-600 bg-emerald-50 dark:bg-emerald-500/10 p-1 rounded-full cursor-pointer"
                                                onClick={(e) => handleCustomerClick(e, selectedContact.phone_number)}
                                            >
                                                <UserCheck className="h-4 w-4" />
                                            </div>
                                        </TooltipTrigger>
                                        <TooltipContent>
                                            <p>Pelanggan (Lihat Data)</p>
                                        </TooltipContent>
                                    </Tooltip>
                                </TooltipProvider>
                            )}
                            {selectedContact.deal ? (
                                <TooltipProvider>
                                    <Tooltip>
                                        <TooltipTrigger asChild>
                                            <div 
                                                className="text-amber-500 hover:text-amber-600 bg-amber-50 dark:bg-amber-500/10 p-1 rounded-full cursor-pointer"
                                            >
                                                <Trophy className="h-4 w-4" />
                                            </div>
                                        </TooltipTrigger>
                                        <TooltipContent>
                                            <p>Pelanggan Deal</p>
                                        </TooltipContent>
                                    </Tooltip>
                                </TooltipProvider>
                            ) : null}
                        </div>
                        <div className="flex flex-row gap-1 ">
                            <p className="text-xs text-gray-500 dark:text-gray-400">{selectedContact.phone_number}
                                <span className=""> {
                                selectedContact?.current_conversation?.last_message_at ? fToNow(selectedContact?.current_conversation?.last_message_at || '') : ''}</span>
                            </p>
                            {selectedContact.labels?.map((item:ContactLabel, index:number) => (
                                <span
                                    key={index}
                                    className={cn("h-4 cursor-pointer")}
                                    style={{
                                        backgroundColor: item.color,
                                        color: item.text_color ?? "#fff",
                                        padding: "1px 6px",
                                        borderRadius: "4px",
                                        fontSize:'9px',
                                        display: "inline-block",
                                        whiteSpace: 'nowrap'
                                    }}
                                >
                                    {item.name}
                                </span>
                            ))}
                            {
                                selectedContact?.branch_id && (
                                    <span className="text-[10px] border px-1 rounded-md h-[18px] text-white" style={{backgroundColor:selectedContact?.branch_bg_color ?? '#666666'}}>{selectedContact?.branch_alias ?? selectedContact?.branch_name}</span>
                                )
                            }
                            {
                                (selectedContact?.address || selectedContact?.city?.name || selectedContact?.province?.name) && (
                                    <span className="font-normal text-xs text-gray-500 dark:text-gray-400">Lokasi : {selectedContact?.address} {selectedContact?.city?.name}{selectedContact?.city?.name && selectedContact?.province?.name ? ', ' : ''} {selectedContact?.province?.name}</span>
                                )
                            }
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-1">
                    {
                        selectedContact?.calling_permission == 'accept' && (selectedContact?.calling_expired == null || new Date(selectedContact?.calling_expired).getTime() > new Date().getTime())
                        && (
                            <Button
                                variant="ghost"
                                size="icon"
                                className="text-gray-500 dark:text-gray-400"
                                disabled={!selectedContact?.is_available}
                                onClick={() => setShowVoiceCall(true)}
                            >
                                <Phone className="h-5 w-5" />
                            </Button>
                        )

                    }
                    
                    <Button
                        variant="ghost"
                        size="icon"
                        className={cn(
                            "text-gray-500 dark:text-gray-400",
                            isSearchOpen && "bg-gray-200 dark:bg-[#111b21]"
                        )}
                        onClick={() => setIsSearchOpen((prev) => !prev)}
                    >
                        <Search className="h-5 w-5" />
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                                <TagIcon className="h-5 w-5" />
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Label</DialogTitle>
                            </DialogHeader>
                            <Form {...formLabel}>
                                <form onSubmit={formLabel.handleSubmit(onSubmitLabel)}>
                                    <div className="flex flex-col flex-wrap gap-2 mb-5 max-h-48 overflow-auto">
                                        
                                        {labels?.map((item: LabelContact, index: number) => (
                                            <FormField
                                                control={formLabel.control}
                                                name="label"
                                                key={index}
                                                render={({ field }) => {
                                                    // Set checked state according to form value
                                                    // Assume formLabel.watch('label') is an array of label ids being checked
                                                    // Otherwise adapt as per your form's structure
                                                    const checked = Array.isArray(formLabel.watch('label'))
                                                        ? formLabel.watch('label').includes(item.id)
                                                        : false;
                                                    return (
                                                        <FormItem>
                                                            <FormControl>
                                                                <div className="flex items-center gap-3">
                                                                    <Checkbox
                                                                        {...field}
                                                                        id={item.id.toString()}
                                                                        className="dark:bg-zinc-600"
                                                                        checked={checked}
                                                                        onCheckedChange={(isChecked) => {
                                                                            const prev = formLabel.getValues('label') || [];
                                                                            if (isChecked) {
                                                                                formLabel.setValue('label', [...prev.filter((id: number) => id !== item.id), item.id]);
                                                                            } else {
                                                                                formLabel.setValue('label', prev.filter((id: number) => id !== item.id));
                                                                            }
                                                                        }}
                                                                    />
                                                                    <Label htmlFor={item.id.toString()} style={{
                                                                        backgroundColor: item.color,
                                                                        color: item.text_color ?? "#fff",
                                                                        padding: "3px 6px",
                                                                        borderRadius: "4px",
                                                                        fontSize: '12px',
                                                                        display: "inline-block",
                                                                        whiteSpace: 'nowrap'
                                                                    }}>{item.name}</Label>
                                                                </div>
                                                            </FormControl>
                                                        </FormItem>
                                                    );
                                                }}
                                            />
                                        ))}
                                    </div>
                                    <DialogFooter>
                                        <Button disabled={editLabel.isPending} type="button" variant="outline" onClick={() => {
                                                setIsDialogOpen(false)
                                        }}>
                                            Cancel
                                        </Button>
                                        {
                                            editLabel.isPending ? 
                                            <Button type="button" className="flex flex-row gap-2" disabled>
                                                <Loader2 className="animate-spin"/>
                                                Simpan
                                            </Button>
                                            :
                                            <Button type="submit">
                                                Simpan
                                            </Button>
                                        }
                                        
                                    </DialogFooter>
                                </form>
                            </Form>
                        </DialogContent>
                    </Dialog>
                
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                                <MoreVertical className="h-5 w-5" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                            <DropdownMenuSub>
                                <DropdownMenuSubTrigger>Lokasi Cabang</DropdownMenuSubTrigger>
                                <DropdownMenuSubContent>
                            {
                                branch?.map((item:Branch, index:number) => (
                                    <DropdownMenuCheckboxItem key={index}
                                            checked={item.id == selectedContact?.branch_id && item.is_access}
                                            disabled={!item.is_access}
                                            onCheckedChange={(e) => {
                                                editContactMutation.mutateAsync({
                                                    first_name:selectedContact?.name,
                                                    last_name:selectedContact?.last_name ?? '',
                                                    account_id:process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE ?? '',
                                                    branch:item.id.toString(),
                                                    phone_number:selectedContact?.phone_number,
                                                    contact_id:selectedContact.id.toString(),
                                                    province_id:selectedContact?.province_id?.toString() ?? '',
                                                    city_id:selectedContact?.city_id?.toString() ?? '',
                                                    address:selectedContact?.address ?? ''
                                                }).then((response) => {
                                                    selectedContact.branch_id = response.data.branch_id
                                                });
                                            }}
                                        >
                                        {item.name}
                                    </DropdownMenuCheckboxItem>
                                ))
                            }
                                </DropdownMenuSubContent>
                            </DropdownMenuSub>
                            <ContactEdit asDropdownItem />
                            <DropdownMenuItem onSelect={() => {
                                setIsChatStatisticsModalOpen(true);
                                refetchContactInfo();
                            }}>
                                Statistik
                            </DropdownMenuItem>
                        </DropdownMenuContent>
                    </DropdownMenu>
                    
                </div>
            </div>
            
            {/* Header Mobile */}
            <div className="py-2 md:hidden w-full  px-4 flex items-center justify-between bg-[#f0f2f5] dark:bg-[#202c33] shrink-0 z-10 border-l border-gray-200 dark:border-gray-800">
                <div className="flex items-center flex-row w-full gap-3 cursor-pointer">
                    {onBack && (
                        <Button
                            variant="ghost"
                            size="icon"
                            className="text-gray-500 dark:text-gray-400 md:hidden"
                            onClick={onBack}
                        >
                            <ArrowLeft className="h-5 w-5" />
                        </Button>
                    )}
                    <div className="flex justify-between items-center w-full flex-row">
                        <div className="flex flex-col gap-1" onClick={() => setIsProfileModalOpen(true)}>
                            <div className="flex items-center gap-2">
                                <h3 className="font-medium text-gray-900 dark:text-gray-100">{selectedContact.name}</h3>
                                {selectedContact.is_customer && (
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <div 
                                                    className="text-emerald-500 hover:text-emerald-600 bg-emerald-50 dark:bg-emerald-500/10 p-1 rounded-full cursor-pointer"
                                                    onClick={(e) => handleCustomerClick(e, selectedContact.phone_number)}
                                                >
                                                    <UserCheck className="h-4 w-4" />
                                                </div>
                                            </TooltipTrigger>
                                            <TooltipContent>
                                                <p>Pelanggan (Lihat Data)</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                )}
                                {selectedContact.deal ? (
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <div 
                                                    className="text-amber-500 hover:text-amber-600 bg-amber-50 dark:bg-amber-500/10 p-1 rounded-full cursor-pointer"
                                                >
                                                    <Trophy className="h-4 w-4" />
                                                </div>
                                            </TooltipTrigger>
                                            <TooltipContent>
                                                <p>Pelanggan Deal</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                ) : null}
                            </div>
                            <div className="flex flex-row gap-1 ">
                                <p className="text-xs text-gray-500 dark:text-gray-400">{selectedContact.phone_number}
                                    <span className=""> {
                                    selectedContact?.current_conversation?.last_message_at ? fToNow(selectedContact?.current_conversation?.last_message_at || '') : ''}</span>
                                </p>
                            </div>
                            <div className="flex flex-row gap-2">
                                {selectedContact.labels?.map((item:ContactLabel, index:number) => (
                                    <span
                                        key={index}
                                        className={cn("h-4 cursor-pointer")}
                                        style={{
                                            backgroundColor: item.color,
                                            color: item.text_color ?? "#fff",
                                            padding: "1px 6px",
                                            borderRadius: "4px",
                                            fontSize:'9px',
                                            display: "inline-block",
                                            whiteSpace: 'nowrap'
                                        }}
                                    >
                                        {item.name}
                                    </span>
                                ))}
                            </div>
                        </div>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                                    <MoreVertical className="h-5 w-5" />
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent>
                                    {
                                        selectedContact?.calling_permission == 'accept' && (selectedContact?.calling_expired == null || new Date(selectedContact?.calling_expired).getTime() > new Date().getTime())
                                        && (
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                className="text-gray-500 dark:text-gray-400"
                                                disabled={!selectedContact?.is_available}
                                                onClick={() => setShowVoiceCall(true)}
                                            >
                                                <Phone className="h-5 w-5" />
                                            </Button>
                                        )

                                    }
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className={cn(
                                            "text-gray-500 dark:text-gray-400",
                                            isSearchOpen && "bg-gray-200 dark:bg-[#111b21]"
                                        )}
                                        onClick={() => setIsSearchOpen((prev) => !prev)}
                                    >
                                        <Search className="h-5 w-5" />
                                    </Button>
                                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                                        <DialogTrigger asChild>
                                            <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                                                <TagIcon className="h-5 w-5" />
                                            </Button>
                                        </DialogTrigger>
                                        <DialogContent>
                                            <DialogHeader>
                                                <DialogTitle>Label</DialogTitle>
                                            </DialogHeader>
                                            <Form {...formLabel}>
                                                <form onSubmit={formLabel.handleSubmit(onSubmitLabel)}>
                                                    <div className="grid grid-cols-2 gap-2 mb-5">
                                                        
                                                        {labels?.map((item: LabelContact, index: number) => (
                                                            <FormField
                                                                control={formLabel.control}
                                                                name="label"
                                                                key={index}
                                                                render={({ field }) => {
                                                                    // Set checked state according to form value
                                                                    // Assume formLabel.watch('label') is an array of label ids being checked
                                                                    // Otherwise adapt as per your form's structure
                                                                    const checked = Array.isArray(formLabel.watch('label'))
                                                                        ? formLabel.watch('label').includes(item.id)
                                                                        : false;
                                                                    return (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <div className="flex items-center gap-3">
                                                                                    <Checkbox
                                                                                        {...field}
                                                                                        id={item.id.toString()}
                                                                                        className="dark:bg-zinc-600"
                                                                                        checked={checked}
                                                                                        onCheckedChange={(isChecked) => {
                                                                                            const prev = formLabel.getValues('label') || [];
                                                                                            if (isChecked) {
                                                                                                formLabel.setValue('label', [...prev.filter((id: number) => id !== item.id), item.id]);
                                                                                            } else {
                                                                                                formLabel.setValue('label', prev.filter((id: number) => id !== item.id));
                                                                                            }
                                                                                        }}
                                                                                    />
                                                                                    <Label htmlFor={item.id.toString()} style={{
                                                                                        backgroundColor: item.color,
                                                                                        color: item.text_color ?? "#fff",
                                                                                        padding: "3px 6px",
                                                                                        borderRadius: "4px",
                                                                                        fontSize: '12px',
                                                                                        display: "inline-block",
                                                                                        whiteSpace: 'nowrap'
                                                                                    }}>{item.name}</Label>
                                                                                </div>
                                                                            </FormControl>
                                                                        </FormItem>
                                                                    );
                                                                }}
                                                            />
                                                        ))}
                                                    </div>
                                                    <DialogFooter>
                                                        <Button disabled={editLabel.isPending} type="button" variant="outline" onClick={() => {
                                                                setIsDialogOpen(false)
                                                        }}>
                                                            Cancel
                                                        </Button>
                                                        {
                                                            editLabel.isPending ? 
                                                            <Button type="button" className="flex flex-row gap-2" disabled>
                                                                <Loader2 className="animate-spin"/>
                                                                Simpan
                                                            </Button>
                                                            :
                                                            <Button type="submit">
                                                                Simpan
                                                            </Button>
                                                        }
                                                        
                                                    </DialogFooter>
                                                </form>
                                            </Form>
                                        </DialogContent>
                                    </Dialog>
                                    <DropdownMenu>
                                        <DropdownMenuTrigger asChild>
                                            <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400">
                                                <MoreVertical className="h-5 w-5" />
                                            </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent>
                                            <DropdownMenuSub>
                                                <DropdownMenuSubTrigger>Lokasi Cabang</DropdownMenuSubTrigger>
                                                <DropdownMenuSubContent>
                                            {
                                                branch?.map((item:Branch, index:number) => (
                                                    <DropdownMenuCheckboxItem key={index}
                                                            checked={item.id == selectedContact?.branch_id}
                                                            onCheckedChange={(e) => {
                                                                editContactMutation.mutateAsync({
                                                                    first_name:selectedContact?.name,
                                                                    last_name:selectedContact?.last_name ?? '',
                                                                    account_id:process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE ?? '',
                                                                    branch:item.id.toString(),
                                                                    phone_number:selectedContact?.phone_number,
                                                                    contact_id:selectedContact.id.toString(),
                                                                    province_id:selectedContact?.province_id?.toString() ?? '',
                                                                    city_id:selectedContact?.city_id?.toString() ?? '',
                                                                    address:selectedContact?.address ?? ''
                                                                }).then((response) => {
                                                                    selectedContact.branch_id = response.data.branch_id
                                                                });
                                                            }}
                                                        >
                                                        {item.name}
                                                    </DropdownMenuCheckboxItem>
                                                ))
                                            }
                                                </DropdownMenuSubContent>
                                            </DropdownMenuSub>
                                            <ContactEdit asDropdownItem />
                                            <DropdownMenuItem onSelect={() => {
                                                setIsChatStatisticsModalOpen(true);
                                                refetchContactInfo();
                                            }}>
                                                Statistik
                                            </DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </div>
                </div>
            </div>
        
            <Dialog open={isProfileModalOpen} onOpenChange={setIsProfileModalOpen}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Info Kontak</DialogTitle>
                    </DialogHeader>
                    <div className="flex flex-col gap-4 py-4">
                        <div className="flex justify-center">
                            <Avatar className="h-24 w-24">
                                <AvatarImage src={contactInfo?.profile_pic_url || selectedContact?.profile_pic_url || undefined} />
                                <AvatarFallback className="text-3xl bg-gray-200 dark:bg-gray-800 text-gray-600 dark:text-gray-400">
                                    {(contactInfo?.name || selectedContact?.name)?.[0]?.toUpperCase() || 'U'}
                                </AvatarFallback>
                            </Avatar>
                        </div>
                        {isContactInfoLoading ? (
                            <div className="flex justify-center items-center py-8">
                                <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                            </div>
                        ) : (
                        <div className="grid grid-cols-2 gap-y-3 gap-x-4 text-sm">
                            <div className="text-gray-500 font-medium">Nama</div>
                            <div className="font-medium">{contactInfo?.name || selectedContact?.name} {contactInfo?.last_name || selectedContact?.last_name || ''}</div>
                            
                            <div className="text-gray-500 font-medium">No HP</div>
                            <div>{contactInfo?.phone_number || selectedContact?.phone_number}</div>
                            
                            <div className="text-gray-500 font-medium">Cabang</div>
                            <div>{contactInfo?.branch_name || selectedContact?.branch_name || '-'}</div>

                            <div className="text-gray-500 font-medium">Pertama Komunikasi</div>
                            <div>{contactInfo?.created_at || selectedContact?.created_at ? format(new Date(contactInfo?.created_at || selectedContact?.created_at), 'dd MMM yyyy HH:mm', { locale: id }) : '-'}</div>
                            
                            <div className="text-gray-500 font-medium col-span-2 mt-2">Pesan Pertama</div>
                            <div className="col-span-2 text-gray-700 dark:text-gray-300 p-3 bg-gray-50 dark:bg-gray-800 rounded-md border border-gray-100 dark:border-gray-700">
                                {contactInfo?.current_conversation?.first_messages || selectedContact?.current_conversation?.first_messages ? (
                                    // <div dangerouslySetInnerHTML={{ __html: fLimitation(parseMessage(selectedContact?.current_conversation?.first_messages?.message_text) || (selectedContact?.current_conversation?.first_messages?.message_type !== 'text' ? selectedContact?.current_conversation?.first_messages?.message_type : '-'), 0, 150) }} />
                                    (contactInfo || selectedContact)?.current_conversation?.first_messages 
                                    ? (
                                        (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "template" ?
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full")}>
                                            {(contactInfo || selectedContact)?.current_conversation?.first_messages?.direction == "outbound" && (
                                                <span className="font-semibold text-sm">{(contactInfo || selectedContact)?.current_conversation?.first_messages?.maded_by_json?.name} : </span>
                                            )} 
                                        <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage((contactInfo || selectedContact)?.current_conversation?.first_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")}>
                                        {(contactInfo || selectedContact)?.current_conversation?.first_messages?.direction == "outbound" && (
                                                <span className="font-semibold text-sm">{(contactInfo || selectedContact)?.current_conversation?.first_messages?.maded_by_json?.name} :</span>
                                        )} <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage((contactInfo || selectedContact)?.current_conversation?.first_messages?.message_text ?? ''),0, 80)}}/>
                                        </span>
                                    )
                                    :  (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "image" ? (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}>
                                            Photo
                                        </span>
                                    ) :  (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "video" ? (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}> 
                                            Video
                                        </span>
                                    ) :  (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "sticker" ? (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}> 
                                            Reaction
                                        </span>
                                    ) :  (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "document" ? (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}> 
                                            Document
                                        </span>
                                    )
                                    :  (contactInfo || selectedContact)?.current_conversation?.first_messages?.message_type == "audio" ? (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}> 
                                            Audio
                                        </span>
                                    )
                                    : (
                                        <span className={cn("text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full")}>
                                            No messages yet
                                        </span>
                                    )
                                ) : '-'}
                            </div>
                            <div className="text-gray-500 font-medium">Jumlah Pesan Masuk</div>
                            <div className="text-blue-600 dark:text-blue-400 font-medium">{contactInfo?.inbound_messages_count ?? selectedContact?.inbound_messages_count ?? '-'}</div>
                            
                            <div className="text-gray-500 font-medium">Jumlah Pesan Dikirim</div>
                            <div className="text-green-600 dark:text-green-400 font-medium">{contactInfo?.outbound_messages_count ?? selectedContact?.outbound_messages_count ?? '-'}</div>
                            <div className="text-gray-500 font-medium">Terakhir Komunikasi</div>
                            <div>{(contactInfo || selectedContact)?.current_conversation?.last_message_at ? format(new Date((contactInfo || selectedContact)?.current_conversation?.last_message_at!), 'dd MMM yyyy HH:mm', { locale: id }) : '-'}</div>
                        </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>

            <ChatStatisticsModal 
                open={isChatStatisticsModalOpen} 
                onOpenChange={setIsChatStatisticsModalOpen} 
                contactInfo={contactInfo || selectedContact} 
                isFetching={isFetchingContactInfo}
            />

            {isSearchOpen && (
                <div className="px-4 py-2 bg-[#f0f2f5] dark:bg-[#202c33] border-b border-gray-200 dark:border-gray-800 z-10">
                    <div className="flex items-center gap-2">
                        <Search className="h-4 w-4 text-gray-500 dark:text-gray-400" />
                        <Input
                            ref={searchInputRef}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="Cari pesan..."
                            className="h-8 bg-white dark:bg-[#111b21] border-none focus-visible:ring-0 text-sm"
                        />
                        {searchQuery && (
                            <Button
                                variant="ghost"
                                size="icon"
                                className="text-gray-500 dark:text-gray-400"
                                onClick={() => setSearchQuery("")}
                            >
                                <X className="h-4 w-4" />
                            </Button>
                        )}
                    </div>
                </div>
            )}

            {/* Messages */}
            <div className="flex-1 h-0 z-10 overflow-auto" ref={scrollAreaRef}
            onScroll={handleScroll}>
                <div className="p-4">
                    {/* Loading indicator for fetching more messages */}
                    {isFetchingNextPage && !isFetchingPageMessage && (
                        <div className="flex justify-center py-2">
                            <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                        </div>
                    )}
                    {isFetchingPageMessage && (
                        <div className="flex justify-center py-2">
                            <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                        </div>
                    )}
                    {(isLoading && !isFetchingPageMessage) ? (
                        <div className="flex items-center justify-center h-full">
                            <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                        </div>
                    ) : (
                        !isFetchingPageMessage && (
                                <div className="flex flex-col gap-3">
                                {filteredConversations.map((conversation, index:number) => (
                                    <MessageBubble
                                        key={index}
                                        content={conversation}
                                        isSent={conversation.direction === 'outbound'}
                                        timestamp={conversation.created_at_date.format}
                                        status={conversation.status as 'sent' | 'delivered' | 'read'}
                                    />
                                ))}
                            </div>
                        )
                    )}
                    {isFetchingPreviousPage && !isFetchingPageMessage && (
                        <div className="flex justify-center py-2">
                            <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                        </div>
                    )}
                </div>
            </div>

            {/* Input Area */}
            <div className="p-3 bg-[#f0f2f5] dark:bg-[#202c33] flex flex-col gap-2 z-10 relative">
                {showEmojiPicker && (
                    <div className="absolute bottom-16 left-0 z-20" onMouseLeave={(e) => setShowEmojiPicker(false)}>
                        <EmojiPicker onEmojiClick={(emojiData:EmojiClickData) => onEmojiClick(emojiData)} emojiStyle={EmojiStyle.NATIVE} />
                    </div>
                )}
                {attachmentFile && (
                    <div className="flex items-start gap-3 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#111b21] p-3">
                        <div className="h-12 w-12 rounded-md bg-gray-100 dark:bg-[#1f2c33] text-gray-600 dark:text-gray-200 flex items-center justify-center overflow-hidden">
                            {attachmentPreview ? (
                                <img src={attachmentPreview} alt={attachmentFile.name} className="h-full w-full object-cover" />
                            ) : (
                                <>
                                    {attachmentType === 'document' && <FileText className="h-5 w-5" />}
                                    {attachmentType === 'video' && <Film className="h-5 w-5" />}
                                    {attachmentType === 'image' && <ImageIcon className="h-5 w-5" />}
                                </>
                            )}
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">{attachmentFile.name}</p>
                            <p className="text-xs text-gray-500 dark:text-gray-400">{(attachmentFile.size / 1024 / 1024).toFixed(2)} MB</p>
                        </div>
                        <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400" onClick={resetComposer}>
                            <X className="h-4 w-4" />
                        </Button>
                    </div>
                )}

                {messageReply && (
                    <>
                        {
                            messageReply?.message_type == "image" ? <ImageReply/>
                            :
                            messageReply?.message_type == "sticker" ? <ImageReply/>
                            :
                            messageReply?.message_type == "template" ? <TemplatetReply/>
                            :
                            <TextReply/>
                        }
                    </>
                )}
                <div className="flex items-center gap-2">
                    <Button variant="ghost" size="icon"
                    disabled={!selectedContact?.is_available || addMessageMutation.isPending}
                    className="text-gray-500 dark:text-gray-400" onClick={() => setShowEmojiPicker(!showEmojiPicker)}>
                        <Smile className="h-6 w-6" />
                    </Button>
                   
                    <DropdownMenu open={openDropDownMessage} onOpenChange={(e) =>  setOpenDropDownMessage(!openDropDownMessage)}>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400"
                                onClick={(e) => setOpenDropDownMessage(!openDropDownMessage)}>
                                <Plus className="h-6 w-6" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start" sideOffset={8} className="w-fit p-2 flex flex-col gap-1">
                            <Button
                                variant="ghost"
                                disabled={!selectedContact?.is_available }
                                className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                onClick={(e) => {
                                    document.getElementById('input-file-image')?.click();
                                }}
                            >
                                <input
                                    id="input-file-image"
                                    type="file"
                                    accept="image/*"
                                    className="hidden"
                                    onChange={handleFileChange('image', true)}
                                />
                                <div className='rounded-lg p-1 bg-green-200 dark:bg-green-500'>
                                    <ImagePlusIcon className='h-5 w-5 '/>
                                </div>
                                Photo
                            </Button>
                                <Button
                                    variant="ghost"
                                    disabled={!selectedContact?.is_available }
                                    className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                    onClick={(e) => {
                                        document.getElementById('input-file-video')?.click();
                                    }}
                                >
                                    <input
                                        id="input-file-video"
                                        type="file"
                                        accept="video/*"
                                        className="hidden"
                                        onChange={handleFileChange('video', true)}
                                    />
                                    <div className='rounded-lg p-1 bg-purple-200 dark:bg-purple-500'>
                                        <Video className='h-5 w-5 '/>
                                    </div>
                                    Video
                                </Button>
                                <Button
                                    variant="ghost"
                                    disabled={!selectedContact?.is_available }
                                    className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                    onClick={(e) => {
                                        document.getElementById('input-file-doc')?.click();
                                    }}
                                >
                                    <input
                                        id="input-file-doc"
                                        type="file"
                                        accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar,.csv,application/*"
                                        className="hidden"
                                        onChange={handleFileChange('document', true)}
                                    />
                                    <div className='rounded-lg p-1 bg-red-200 dark:bg-red-500'>
                                        <FileText className='h-5 w-5 '/>
                                    </div>
                                    Document
                                </Button>
                                <Button
                                    variant="ghost"
                                    className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                    onClick={(e) => {
                                        setOpenMessageTemplate(true)
                                        setWithoutContact(false);
                                    }}
                                >
                                    <div className='rounded-lg p-1 bg-blue-200 dark:bg-blue-500'>
                                        <LayoutPanelTop className='h-5 w-5 '/>
                                    </div>
                                    Template
                                </Button>
                                <Button
                                    variant="ghost"
                                    disabled={!selectedContact?.is_available }
                                    className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                    onClick={(e) => {
                                        setOpenMarketingKitText(true);
                                    }}
                                >
                                    <div className='rounded-lg p-1 bg-yellow-200 dark:bg-yellow-500'>
                                        <TagIcon className='h-5 w-5 '/>
                                    </div>
                                    Marketing Kit Teks
                                </Button>
                                <Button
                                    variant="ghost"
                                    disabled={!selectedContact?.is_available }
                                    className="flex items-center gap-2 w-full justify-start text-gray-700 dark:text-gray-200 px-2 py-2"
                                    onClick={(e) => {
                                        setOpenMarketingKitBanner(true);
                                    }}
                                >
                                    <div className='rounded-lg p-1 bg-orange-200 dark:bg-orange-500'>
                                        <ImageIcon className='h-5 w-5 '/>
                                    </div>
                                    Marketing Kit Banner
                                </Button>
                        </DropdownMenuContent>
                    </DropdownMenu>
                
                    <Textarea
                        value={newMessage}
                        ref={refTextArea}
                        disabled={!selectedContact?.is_available || addMessageMutation.isPending}
                        onChange={(e) => {
                            setNewMessage(e.target.value);
                            if (selectedContact?.id) {
                                setDraftMessage(selectedContact.id.toString(), e.target.value);
                            }
                        }}
                        onKeyDown={handleKeyPress}
                        placeholder={
                            selectedContact?.is_available 
                                ? attachmentFile ? "Tambahkan caption" : "Type a message" 
                                : "Pesan terakhir sudah melebihi waktu 24 jam. Kirimkan pesan template untuk membuka chat"
                        }
                        className="flex-1 bg-white  dark:bg-[#2a3942] min-h-0 border-none focus-visible:ring-0 rounded-md px-3 text-base placeholder:text-left placeholder:items-center resize-none"
                        style={{ minHeight: '2.25rem', maxHeight: '180px', overflow: 'auto', height: heighInput }}
                        rows={1}
                        onInput={e => {
                            const target = e.target as HTMLTextAreaElement;
                            target.style.height = 'auto';
                            target.style.height = `${Math.min(target.scrollHeight, 180)}px`;
                        }}
                        // Support pasting image from clipboard
                        onPaste={async (e) => {
                            if (!(e.clipboardData && e.clipboardData.items)) return;
                            for (let i = 0; i < e.clipboardData.items.length; i++) {
                                const item = e.clipboardData.items[i];
                                if (item.type.indexOf('image') !== -1) {
                                    const file = item.getAsFile();
                                    if (file) {
                                        handleFileChange('image')({ target: { files: [file] } } as any);
                                        e.preventDefault();
                                    }
                                } else if (item.type.indexOf('video') !== -1) {
                                    const file = item.getAsFile();
                                    if (file) {
                                        handleFileChange('video')({ target: { files: [file] } } as any);
                                        e.preventDefault();
                                    }
                                } else if (
                                    item.type === "application/pdf" ||
                                    item.type.startsWith("application/") ||
                                    item.type.startsWith("text/") ||
                                    (item.type === "" && item.getAsFile()?.name?.match(/\.(docx?|xlsx?|pptx?|txt|zip|rar|csv)$/i))
                                ) {
                                    const file = item.getAsFile();
                                    if (file) {
                                        handleFileChange('document')({ target: { files: [file] } } as any);
                                        e.preventDefault();
                                    }
                                }
                            }
                        }}
                    />
                    <Button variant="ghost" size="icon" className="text-gray-500 dark:text-gray-400"
                    disabled={!selectedContact?.is_available || addMessageMutation.isPending}
                    onClick={handleSendMessage}>
                        {
                            addMessageMutation.isPending ?
                            <Loader2 className='h-6 w-6 animate-spin text-gray-500'/>
                            :
                            <Send className="h-6 w-6" />
                        }
                    </Button>
                </div>
            </div>

            <MarketingKitTextDialog 
                open={openMarketingKitText} 
                onOpenChange={setOpenMarketingKitText} 
            />
            <MarketingKitBannerDialog 
                open={openMarketingKitBanner} 
                onOpenChange={setOpenMarketingKitBanner} 
            />
        </div>
    );
};

export default ChatWindow;
