'use client'
import Layout from "@/hoc/Layout"
import { NextPage } from "next"
import { useSearchParams, useRouter } from "next/navigation"
import { useState, useEffect, Suspense } from "react"
import Menu from "../components/Menu"
import ChatSidebar from "./components/ChatSidebar"
import ChatMessages from "./components/ChatMessages"
import { isAuthenticated } from "@/config/func"
import { useCreateChat } from "../hooks/useChatData"

const ChatContent: React.FC = () => {
    const searchParams = useSearchParams()
    const shopId = searchParams.get('shopId')
    const createChat = useCreateChat()
    const router = useRouter()

    const [selectedChatId, setSelectedChatId] = useState<string>('')
    const [isUserAuthenticated, setIsUserAuthenticated] = useState<boolean | null>(null)
    const [isLoading, setIsLoading] = useState(true)
    const [isInitialized, setIsInitialized] = useState(false)

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

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

            // کمی صبر کن تا کامپوننت‌ها آماده شوند
            setTimeout(() => {
                setIsInitialized(true)
            }, 100)
        }

        checkAuth()
    }, [router])

    const handleChatSelect = (chatId: string) => {
        setSelectedChatId(chatId)
    }

    useEffect(() => {

        if (shopId) {
            createChat.mutate({ sellerId: shopId })
        }

    }, [shopId, createChat])

    // Show loading while checking authentication
    if (isLoading) {
        return (
            <Layout>
                <div className="p-3 sm:p-4 md:p-6">
                    <Menu pageActive='chat' />
                    <div className="mt-6 flex items-center justify-center h-[calc(100vh-200px)] min-h-[600px]">
                        <div className="text-center">
                            <div className="text-lg text-gray-600 mb-2">در حال بررسی...</div>
                            <div className="text-sm text-gray-400">لطفاً صبر کنید</div>
                        </div>
                    </div>
                </div>
            </Layout>
        )
    }

    // Don't render chat if user is not logged in (will redirect)
    if (!isUserAuthenticated) {
        return (
            <Layout>
                <div className="p-3 sm:p-4 md:p-6">
                    <Menu pageActive='chat' />
                    <div className="mt-6 flex items-center justify-center h-[calc(100vh-200px)] min-h-[600px]">
                        <div className="text-center">
                            <div className="text-lg text-gray-600 mb-2">در حال انتقال...</div>
                            <div className="text-sm text-gray-400">لطفاً صبر کنید</div>
                        </div>
                    </div>
                </div>
            </Layout>
        )
    }




    return (
        <Layout>
            <div className="p-3 sm:p-4 md:p-6">
                <Menu pageActive='chat' />

                <div className="mt-6 h-[calc(100vh-200px)] min-h-[600px]">
                    {/* Chat Section - Sidebar + Messages */}
                    <div className="flex border border-gray-200 shadow-sm rounded-xl bg-white h-full">
                        {/* Chat Sidebar - Left Side */}
                        <div className="w-80 border-r border-gray-200">
                            {isInitialized ? (
                                <ChatSidebar
                                    selectedChatId={selectedChatId}
                                    onChatSelect={handleChatSelect}
                                />
                            ) : (
                                <div className="flex items-center justify-center h-full">
                                    <div className="text-center">
                                        <div className="text-sm text-gray-500">در حال بارگذاری چت...</div>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Chat Messages - Right Side */}
                        <div className="flex-1 min-w-0">
                            {isInitialized ? (
                                <ChatMessages
                                    chatId={selectedChatId}
                                />
                            ) : (
                                <div className="flex items-center justify-center h-full">
                                    <div className="text-center">
                                        <div className="text-sm text-gray-500">در حال بارگذاری پیام‌ها...</div>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </Layout>
    )
}

const Chat: NextPage = () => {
    return (
        <Suspense fallback={
            <Layout>
                <div className="p-3 sm:p-4 md:p-6">
                    <Menu pageActive='chat' />
                    <div className="mt-6 flex items-center justify-center h-[calc(100vh-200px)] min-h-[600px]">
                        <div className="text-center">
                            <div className="text-lg text-gray-600 mb-2">در حال بارگذاری...</div>
                            <div className="text-sm text-gray-400">لطفاً صبر کنید</div>
                        </div>
                    </div>
                </div>
            </Layout>
        }>
            <ChatContent />
        </Suspense>
    )
}

export default Chat