'use client'
import { useState, useRef, useEffect, useMemo } from 'react'
import Image from 'next/image'
import { Send, Shop } from 'iconsax-react'
import { useSocket } from '../hooks/useSocket'
import { Message as SocketMessage } from '../service/SocketService'
import { useChatDetail, useMarkChatAsRead } from '../../hooks/useChatData'
import { useQueryClient } from '@tanstack/react-query'
import { isAuthenticated } from '@/config/func'
import { ChatMessage as APIMessage } from '../../types/ProfileTypes'

interface Message {
    id: string
    text: string
    time: string
    sender: 'user' | 'admin'
    status?: 'sent' | 'delivered' | 'read'
}

interface ChatMessagesProps {
    chatId?: string
}

export default function ChatMessages({ chatId }: ChatMessagesProps) {
    const [messageText, setMessageText] = useState('')
    const [isTyping, setIsTyping] = useState(false)
    const [selectedFile, setSelectedFile] = useState<File | null>(null)
    const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
    const messagesEndRef = useRef<HTMLDivElement>(null)
    const messagesContainerRef = useRef<HTMLDivElement>(null)
    const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null)
    const fileInputRef = useRef<HTMLInputElement>(null)
    const markedAsReadRef = useRef<Set<string>>(new Set())

    // Check authentication on mount
    useEffect(() => {
        const checkAuth = async () => {
            const authenticated = await isAuthenticated()
            setIsUserAuthenticated(authenticated)
        }
        checkAuth()
    }, [])

    const {
        isConnected,
        joinChat,
        leaveChat,
        sendMessage,
        onNewMessage,
        onError,
        connect
    } = useSocket()

    const queryClient = useQueryClient()
    const { data: chatData, isLoading, error } = useChatDetail(chatId)

    const markAsRead = useMarkChatAsRead()

    // Convert API messages to component format
    const messages: Message[] = useMemo(() => {
        const apiMessages = chatData?.results?.messages
        if (Array.isArray(apiMessages)) {
            return apiMessages.map((msg: APIMessage) => ({
                id: msg._id,
                text: msg.content,
                time: new Date(msg.createdAt).toLocaleTimeString('fa-IR', {
                    hour: '2-digit',
                    minute: '2-digit'
                }),
                sender: msg.senderRef === 'User' ? 'user' : 'admin',
                status: msg.status
            }))
        }
        return []
    }, [chatData?.results?.messages])

    const scrollToBottom = () => {
        if (messagesContainerRef.current) {
            messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight
        }
    }

    useEffect(() => {
        scrollToBottom()
    }, [messages])

    // اتصال به سوکت وقتی chatId تنظیم شده و کاربر لاگین کرده
    useEffect(() => {
        if (chatId && chatId !== '' && isUserAuthenticated === true && !isConnected) {
            console.log('🔌 اتصال به سوکت برای چت...')
            connect().catch((error) => {
                console.error('❌ خطا در اتصال سوکت:', error.message)

                // اگر توکن expired است، پیام نمایش بده
                if (error.message === 'توکن منقضی شده' || error.message === 'توکن یافت نشد') {
                    console.log('🔐 توکن نامعتبر برای چت')
                }
            })
        }
    }, [chatId, isUserAuthenticated, isConnected, connect])

    // اتصال به چت وقتی سوکت متصل شد
    useEffect(() => {
        if (chatId && chatId !== '' && isConnected) {
            console.log('🔗 اتصال به چت:', chatId)
            joinChat(chatId)
            return () => {
                leaveChat(chatId)
            }
        }
    }, [chatId, isConnected, joinChat, leaveChat])

    // Mark messages as read - فقط یک بار برای هر chatId
    useEffect(() => {
        if (chatId && chatId !== '' && isUserAuthenticated === true && isConnected) {
            // بررسی اینکه آیا قبلاً برای این chatId mark as read کرده‌ایم
            if (!markedAsReadRef.current.has(chatId)) {
                console.log('📖 mark as read برای چت:', chatId)
                markedAsReadRef.current.add(chatId)
                markAsRead.mutate(chatId)
            } else {
                console.log('ℹ️ چت قبلاً mark as read شده:', chatId)
            }
        }
    }, [chatId, isUserAuthenticated, isConnected, markAsRead])

    // Listen for new messages
    useEffect(() => {
        const handleNewMessage = (socketMessage: unknown) => {
            const message = socketMessage as SocketMessage
            if (message.chatId === chatId) {
                console.log('New message received:', message)
                // Invalidate chat detail query to refetch messages
                // This will handle both sent and received messages
                queryClient.invalidateQueries({ queryKey: ['chat', 'detail', chatId] })
                // Scroll to bottom after a short delay to ensure new message is rendered
                setTimeout(scrollToBottom, 100)
            }
        }

        const handleError = (error: unknown) => {
            const err = error as { message: string }
            console.error('🚨 خطای چت:', err.message)
            // You can show a toast notification here
            if (err.message === 'اتصال سوکت برقرار نیست') {
                console.warn('⚠️ راهنمایی: اگر این خطا تکرار می‌شود، احتمالاً سرور سوکت اجرا نمی‌شود یا قابل دسترسی نیست.')
            }
        }

        onNewMessage(handleNewMessage)
        onError(handleError)

        return () => {
            // Cleanup will be handled by the hook
        }
    }, [chatId, onNewMessage, onError, queryClient])

    const handleTyping = () => {
        if (!isTyping) {
            setIsTyping(true)
            // Here you could emit a typing event to the server
            // socketService.emit('typing', { chatId: chatId })
        }

        // Clear previous timeout
        if (typingTimeoutRef.current) {
            clearTimeout(typingTimeoutRef.current)
        }

        // Set new timeout to stop typing indicator
        typingTimeoutRef.current = setTimeout(() => {
            setIsTyping(false)
            // socketService.emit('stopTyping', { chatId: chatId })
        }, 2000)
    }

    const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0]
        if (file) {
            setSelectedFile(file)
            console.log('📎 فایل انتخاب شد:', file.name, file.size, 'bytes')
        }
    }

    // const handleAttachClick = () => {
    //     fileInputRef.current?.click()
    // }

    const handleSend = () => {
        if ((messageText.trim() || selectedFile) && chatId) {
            const content = messageText.trim()
            setMessageText('')
            setIsTyping(false)
            setSelectedFile(null)

            // Clear typing timeout
            if (typingTimeoutRef.current) {
                clearTimeout(typingTimeoutRef.current)
            }

            // For now, just send text message
            // TODO: Implement file upload when server supports it
            if (content) {
                const receiver = chat?.seller
                if (receiver) {
                    sendMessage(chatId, content, receiver)
                    // Invalidate query to show sent message immediately after socket event
                    // Note: This might cause duplicate if socket event also invalidates
                    setTimeout(() => {
                        queryClient.invalidateQueries({ queryKey: ['chat', 'detail', chatId] })
                    }, 500)
                } else {
                    console.error('❌ receiver یافت نشد - نمی‌توان پیام ارسال کرد')
                }
            }

            // Scroll to bottom after sending
            setTimeout(scrollToBottom, 100)
        }
    }

    const chat = chatData?.results?.chat
    const seller = chat?.shopLogo

    return (
        <div className="bg-white flex flex-col h-full">
            {/* Header */}
            <div className="px-6 py-4 border-b border-gray-100 bg-white">
                {isLoading ? (
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gray-200 rounded-full animate-pulse"></div>
                        <div>
                            <div className="w-20 h-4 bg-gray-200 rounded animate-pulse mb-1"></div>
                            <div className="w-12 h-3 bg-gray-200 rounded animate-pulse"></div>
                        </div>
                    </div>
                ) : error ? (
                    <div className="text-center text-red-500">
                        <p className="text-sm">خطا در بارگذاری چت</p>
                    </div>
                ) : seller ? (
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <div className="relative">
                                <div className="w-10 h-10 bg-gradient-to-br from-primary/10 to-primary/20 rounded-full flex items-center justify-center overflow-hidden">
                                    {seller.logo ? (
                                        <Image
                                            src={seller.logo}
                                            alt={chat?.sellerRef || 'فروشگاه'}
                                            fill
                                            className="object-cover"
                                        />
                                    ) : (
                                        <Shop size={18} color="#1a73e8" variant="Bold" />
                                    )}
                                </div>
                                {/* وضعیت آنلاین در این API موجود نیست */}
                            </div>
                            <div>
                                <h3 className="font-semibold text-gray-900 text-sm">{chat?.sellerRef || 'فروشگاه'}</h3>
                                <p className="text-xs text-gray-500">
                                    آفلاین
                                </p>
                            </div>
                        </div>

                    </div>
                ) : (
                    <div className="text-center text-gray-500">
                        <p className="text-sm">چتی انتخاب نشده</p>
                    </div>
                )}
            </div>

            {/* Messages Area */}
            <div ref={messagesContainerRef} className="flex-1 overflow-y-auto bg-gray-50/30">
                {/* Socket Status Alert */}
                {!isConnected && (
                    <div className="px-6 py-3">
                        <div className="bg-blue-50 border border-blue-200 rounded-lg px-4 py-3">
                            <div className="text-xs text-blue-800 leading-relaxed">
                                <div className="font-semibold mb-2">ℹ️ اتصال به چت</div>
                                <div className="space-y-1">
                                    <div>• لطفاً چند لحظه صبر کنید</div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Alert */}
                <div className="px-6 py-3">
                    <div className="bg-amber-50 border border-amber-200 rounded-lg px-4 py-3">
                        <p className="text-xs text-amber-800 leading-relaxed">
                            لطفا از ارسال اطلاعات مهم، شخصی و یا نامربوط بپرهیزید. گفتگوهای شما محرمانه است.
                        </p>
                    </div>
                </div>

                {/* Messages */}
                <div className="px-6 pb-4 space-y-4">
                    {isLoading ? (
                        <div className="space-y-4">
                            {[1, 2, 3].map((i) => (
                                <div key={i} className={`flex ${i % 2 === 0 ? 'justify-start' : 'justify-end'}`}>
                                    <div className="max-w-[70%]">
                                        <div className="w-16 h-4 bg-gray-200 rounded animate-pulse mb-2"></div>
                                        <div className="rounded-2xl px-4 py-3 bg-gray-200 animate-pulse">
                                            <div className="w-32 h-4 bg-gray-100 rounded"></div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : error ? (
                        <div className="text-center text-red-500 py-8">
                            <p className="text-sm">خطا در بارگذاری پیام‌ها</p>
                        </div>
                    ) : messages.length > 0 ? (
                        messages.map((message, index) => {
                            const isFirstInGroup = index === 0 || messages[index - 1].sender !== message.sender
                            const senderName = message.sender === 'user' ? 'شما' :
                                (typeof chat?.sellerRef === 'string' ? chat.sellerRef : 'فروشگاه')

                            return (
                                <div
                                    key={message.id}
                                    className={`flex ${message.sender === 'user' ? 'justify-start' : 'justify-end'}`}
                                >
                                    <div className={`max-w-[70%] ${message.sender === 'user' ? 'mr-0' : 'ml-0'}`}>
                                        {isFirstInGroup && (
                                            <div className={`flex items-center gap-2 mb-2 ${message.sender === 'user' ? 'justify-start' : 'justify-end'}`}>
                                                <span className="text-xs text-gray-500 font-medium">
                                                    {senderName}
                                                </span>
                                                <span className="text-xs text-gray-400">{message.time}</span>
                                            </div>
                                        )}

                                        <div
                                            className={`rounded-2xl px-4 py-3 shadow-sm ${message.sender === 'user'
                                                ? 'bg-white text-gray-800 border border-gray-100'
                                                : 'bg-primary text-primary-foreground'
                                                }`}
                                        >
                                            <p className="text-sm leading-relaxed">{typeof message.text === 'string' ? message.text : 'پیام نامعتبر'}</p>
                                        </div>

                                        {message.sender === 'user' && (
                                            <div className="flex justify-start mt-1">
                                                <div className="flex items-center gap-1">
                                                    <span className="text-xs text-gray-400">{message.time}</span>
                                                    {message.status === 'read' && (
                                                        <div className="flex -space-x-1">
                                                            <div className="w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center">
                                                                <div className="w-1 h-1 bg-white rounded-full"></div>
                                                            </div>
                                                            <div className="w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center">
                                                                <div className="w-1 h-1 bg-white rounded-full"></div>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )
                        })
                    ) : (
                        <div className="text-center text-gray-500 py-8">
                            <p className="text-sm">هنوز پیامی ارسال نشده</p>
                        </div>
                    )}

                    {/* Typing Indicator */}
                    {isTyping && (
                        <div className="flex justify-end mb-4">
                            <div className="max-w-[70%]">
                                <div className="flex items-center gap-2 mb-2 justify-end">
                                    <span className="text-xs text-gray-500 font-medium">
                                        {chat?.sellerRef || 'فروشگاه'}
                                    </span>
                                </div>
                                <div className="bg-primary text-primary-foreground rounded-2xl px-4 py-3 shadow-sm">
                                    <div className="flex items-center gap-1">
                                        <div className="flex gap-1">
                                            <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                                            <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                                            <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                                        </div>
                                        <span className="text-xs text-white ml-2">در حال تایپ...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    <div ref={messagesEndRef} />
                </div>
            </div>

            {/* Input Area - Only show when chat is selected */}
            {chatId && chatId !== '' && (
                <div className="border-t border-gray-100 px-6 py-4 bg-white">
                    <div className="flex items-center gap-3">
                        {/* <button
                            onClick={handleAttachClick}
                            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors flex-shrink-0"
                        >
                            <AttachCircle color='#8C90A3' size={20} />
                        </button> */}

                        {/* Hidden file input */}
                        <input
                            ref={fileInputRef}
                            type="file"
                            accept="image/*,video/*,audio/*,application/*,text/*"
                            onChange={handleFileSelect}
                            className="hidden"
                        />

                        <div className="flex-1 relative">
                            {/* File Preview */}
                            {selectedFile && (
                                <div className="mb-2 p-2 bg-blue-50 border border-blue-200 rounded-lg flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <div className="w-8 h-8 bg-blue-100 rounded flex items-center justify-center">
                                            📎
                                        </div>
                                        <div>
                                            <p className="text-xs font-medium text-blue-900">{selectedFile.name}</p>
                                            <p className="text-xs text-blue-600">{(selectedFile.size / 1024).toFixed(1)} KB</p>
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => setSelectedFile(null)}
                                        className="text-blue-500 hover:text-blue-700 p-1"
                                    >
                                        ✕
                                    </button>
                                </div>
                            )}

                            <textarea
                                value={messageText}
                                onChange={(e) => {
                                    setMessageText(e.target.value)
                                    handleTyping()
                                }}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter' && !e.shiftKey) {
                                        e.preventDefault()
                                        handleSend()
                                    }
                                }}
                                placeholder={selectedFile ? "توضیحات فایل را بنویسید..." : "پیام خود را بنویسید..."}
                                rows={1}
                                className="w-full resize-none bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent max-h-32"
                                style={{ minHeight: '44px' }}
                            />
                        </div>

                        <button
                            onClick={handleSend}
                            disabled={(!messageText.trim() && !selectedFile) || !isConnected}
                            className={`p-3 -mt-1 rounded-xl transition-all flex-shrink-0 ${(messageText.trim() || selectedFile) && isConnected
                                ? 'bg-primary hover:bg-primary/90 text-primary-foreground '
                                : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                                }`}
                        >
                            <Send color='#fff' size={18} className="rotate-180" variant="Bold" />
                        </button>
                    </div>

                    <p className="text-xs text-gray-400 mt-2 text-center">
                        پیام شما بعد از ارسال قابل حذف نیست
                    </p>
                </div>
            )}
        </div>
    )
}
