'use client'

import { Suspense, useCallback, useEffect, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useLobsters, type LobsterWithStatus } from '@/hooks/useLobsters'
import { LobsterSidebar } from '@/components/LobsterSidebar'
import { ChatContainer } from '@/components/ChatContainer'
import { FloatingAvatar } from '@/components/FloatingAvatar'

export default function ChatPage() {
  return (
    <Suspense
      fallback={
        <main className="flex min-h-screen items-center justify-center">
          <p className="text-sm text-slate-500">Loading...</p>
        </main>
      }
    >
      <ChatPageInner />
    </Suspense>
  )
}

function ChatPageInner() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { user, loading: authLoading, token } = useAuth()
  const { lobstersWithStatus, fetchApiKeys } = useLobsters()

  const [activeLobster, setActiveLobster] = useState<LobsterWithStatus | null>(null)
  const [sidebarCollapsed, setSidebarCollapsed] = useState(true)

  // Auth guard
  useEffect(() => {
    if (authLoading) return
    if (!user || !token) {
      router.replace('/login')
    }
  }, [user, token, authLoading, router])

  // Fetch lobster list on mount
  useEffect(() => {
    if (user) void fetchApiKeys()
  }, [user, fetchApiKeys])

  // Restore selection from URL query param
  useEffect(() => {
    const lobsterIdFromUrl = searchParams.get('lobsterId')
    if (lobsterIdFromUrl && !activeLobster && lobstersWithStatus.length > 0) {
      const found = lobstersWithStatus.find((l) => l.id === lobsterIdFromUrl)
      if (found) setActiveLobster(found)
    }
  }, [searchParams, lobstersWithStatus, activeLobster])

  // Keep activeLobster in sync with fresh status data
  useEffect(() => {
    if (activeLobster) {
      const fresh = lobstersWithStatus.find((l) => l.id === activeLobster.id)
      if (fresh && fresh.isOnline !== activeLobster.isOnline) {
        setActiveLobster(fresh)
      }
    }
  }, [lobstersWithStatus, activeLobster])

  const handleSelect = useCallback(
    (lobster: LobsterWithStatus) => {
      setActiveLobster(lobster)
      setSidebarCollapsed(true)
      // Update URL without navigation
      const url = new URL(window.location.href)
      url.searchParams.set('lobsterId', lobster.id)
      window.history.replaceState(null, '', url.toString())
    },
    [],
  )

  if (authLoading || !user || !token) {
    return (
      <main className="flex min-h-screen items-center justify-center">
        <p className="text-sm text-slate-500">Loading...</p>
      </main>
    )
  }

  return (
    <main className="flex h-screen overflow-hidden bg-white">
      <LobsterSidebar
        lobsters={lobstersWithStatus}
        activeLobsterId={activeLobster?.id ?? null}
        onSelect={handleSelect}
        collapsed={sidebarCollapsed}
        onToggle={() => setSidebarCollapsed((c) => !c)}
      />

      <div className="flex flex-1 flex-col">
        {activeLobster ? (
          <ChatContainer
            key={activeLobster.id}
            lobsterId={activeLobster.id}
            lobsterName={activeLobster.name}
            isOnline={activeLobster.isOnline}
            userName={user.name ?? user.email}
          />
        ) : (
          <div className="flex flex-1 items-center justify-center">
            <div className="text-center">
              <p className="text-sm text-slate-500 pl-10 md:pl-0">
                Select a lobster to start chatting
              </p>
            </div>
          </div>
        )}
      </div>

      <FloatingAvatar apikeyId={activeLobster?.id ?? null} />
    </main>
  )
}
