'use client'
import { Shop, SearchNormal1 } from 'iconsax-react'
import Image from 'next/image'
import { useState, useEffect } from 'react'
import { useSocket } from '../hooks/useSocket'
import { useChatList } from '../../hooks/useChatData'
import { useRouter } from 'next/navigation'
import { isAuthenticated } from '@/config/func'

interface ChatSidebarProps {
    selectedChatId?: string
    onChatSelect?: (chatId: string) => void
}

export default function ChatSidebar({ selectedChatId, onChatSelect }: ChatSidebarProps) {
    const [searchQuery, setSearchQuery] = useState('')
    const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
    const [isConnecting, setIsConnecting] = useState(false)
    const router = useRouter()
    const { onUserOnline, onUserOffline, connect, isConnected } = useSocket()
    const { data: chatData, isLoading, error } = useChatList({
        enabled: isUserAuthenticated === true && isConnected // Only fetch if user is logged in AND socket is connected
    })

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

            if (!authenticated) {
                console.log('🔐 کاربر login نکرده یا توکن expire شده، redirect به صفحه ورود')
                router.push('/auth')
                return
            }

            // اتصال به سوکت اگر متصل نیست
            if (!isConnected && !isConnecting) {
                console.log('🔌 شروع اتصال به سوکت...')
                setIsConnecting(true)
                connect()
                    .then(() => {
                        console.log('✅ اتصال سوکت موفق')
                        setIsConnecting(false)
                    })
                    .catch((error) => {
                        console.log('❌ اتصال سوکت شکست خورد:', error.message)
                        setIsConnecting(false)

                        // اگر توکن expired است، redirect به login
                        if (error.message === 'توکن منقضی شده' || error.message === 'توکن یافت نشد') {
                            console.log('🔐 توکن نامعتبر، redirect به صفحه ورود')
                            router.push('/auth')
                        }
                    })
            } else if (isConnected) {
                console.log('ℹ️ اتصال سوکت قبلاً برقرار شده')
            }
        }

        checkAuth()
    }, [connect, router, isConnected, isConnecting])

    // Listen for user online/offline events
    useEffect(() => {
        const handleUserOnline = (userId: unknown) => {
            const id = userId as string
            console.log('🟢 کاربر آنلاین شد:', id)
            // Here you could update the chat list to reflect online status
            // For now, we'll just log it
        }

        const handleUserOffline = (userId: unknown) => {
            const id = userId as string
            console.log('🔴 کاربر آفلاین شد:', id)
            // Here you could update the chat list to reflect offline status
        }

        onUserOnline(handleUserOnline)
        onUserOffline(handleUserOffline)

        return () => {
            // Cleanup will be handled by the hook
        }
    }, [onUserOnline, onUserOffline])

    const chats = Array.isArray(chatData?.results?.chats) ? chatData.results.chats : []

    const filteredChats = chats.filter(chat => {
        if (!chat || typeof chat !== 'object') return false
        if (!chat.seller || typeof chat.seller !== 'object') return false
        const fullName = chat.seller.fullName
        if (typeof fullName !== 'string') return false
        return fullName.toLowerCase().includes(searchQuery.toLowerCase())
    })

    const handleChatClick = (chatId: string) => {
        if (onChatSelect) {
            onChatSelect(chatId)
        }
    }

    return (
        <div className="w-full bg-white flex flex-col h-full">
            {/* Header */}
            <div className="p-4 border-b border-gray-100">
                <h2 className="text-lg font-bold text-gray-900 mb-4">گفتگوها</h2>

                {/* Search */}
                <div className="relative">
                    <SearchNormal1 size={20} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400" />
                    <input
                        type="text"
                        placeholder="جستجو در گفتگوها..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pr-10 pl-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    />
                </div>
            </div>

            {/* Chat List */}
            <div className="flex-1 overflow-y-auto">
                {isLoading ? (
                    <div className="divide-y divide-gray-50">
                        {[1, 2, 3, 4, 5].map((i) => (
                            <div key={i} className="p-4">
                                <div className="flex items-start gap-3">
                                    {/* Avatar Skeleton */}
                                    <div className="relative flex-shrink-0">
                                        <div className="w-12 h-12 bg-gray-200 rounded-full animate-pulse"></div>
                                    </div>

                                    {/* Content Skeleton */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center justify-between mb-2">
                                            <div className="h-4 bg-gray-200 rounded animate-pulse w-24"></div>
                                            <div className="h-3 bg-gray-200 rounded animate-pulse w-12"></div>
                                        </div>
                                        <div className="h-3 bg-gray-200 rounded animate-pulse w-32 mb-2"></div>
                                        <div className="h-3 bg-gray-200 rounded animate-pulse w-20"></div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : error ? (
                    <div className="p-8 text-center text-red-400">
                        <p className="text-sm">خطا در بارگذاری گفتگوها</p>
                    </div>
                ) : (
                    <div className="divide-y divide-gray-50">
                        {filteredChats.map((chat) => (
                            <div
                                key={chat._id}
                                onClick={() => handleChatClick(chat._id)}
                                className={`p-4 cursor-pointer transition-all hover:bg-gray-50 ${selectedChatId === chat._id ? 'bg-primary/5 border-r-2 border-r-primary' : ''
                                    }`}
                            >
                                <div className="flex items-start gap-3">
                                    {/* Avatar */}
                                    <div className="relative flex-shrink-0">
                                        <div className="w-12 h-12 bg-gradient-to-br from-primary/10 to-primary/20 rounded-full flex items-center justify-center overflow-hidden">
                                            {chat.shopLogo?.logo ? (
                                                <Image
                                                    src={chat.shopLogo.logo}
                                                    alt={chat.seller?.fullName || 'فروشنده'}
                                                    fill
                                                    className="object-cover"
                                                />
                                            ) : (
                                                <Shop size={20} className="text-primary" variant="Bold" />
                                            )}
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center justify-between mb-1">
                                            <h3 className="font-semibold text-gray-900 text-sm truncate">
                                                {typeof chat.seller?.fullName === 'string' ? chat.seller.fullName : 'فروشنده'}
                                            </h3>
                                            <span className="text-xs text-gray-400 flex-shrink-0">
                                                {new Date(chat.updatedAt).toLocaleDateString('fa-IR')}
                                            </span>
                                        </div>

                                        <p className="text-xs text-gray-500 truncate mb-2">
                                            {typeof chat.lastMessage === 'string' ? chat.lastMessage : 'گفتگوی جدید'}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {!isLoading && !error && filteredChats.length === 0 && (
                    <div className="p-8 text-center text-gray-400">
                        <p className="text-sm">گفتگویی یافت نشد</p>
                    </div>
                )}
            </div>
        </div>
    )
}
