import { useCallback, useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAIChatStore } from '@/store/aiChatStore'
import { ChatPanel } from '@/components/ai-chat/ChatPanel'
import { ChatToolbar } from '@/components/ai-chat/ChatToolbar'
import { EmptyPreview } from '@/components/ai-chat/EmptyPreview'
import { StaticTreePreview } from '@/components/ai-chat/StaticTreePreview'
import { Spinner } from '@/components/common/Spinner'
import { getTreeEditorPath } from '@/lib/routing'
import { toast } from '@/lib/toast'
import type { TreeStructure } from '@/types'

export function AIChatBuilderPage() {
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const flowType = searchParams.get('type') === 'procedural' ? 'procedural' : 'troubleshooting'

  const {
    sessionId,
    status,
    currentPhase,
    messages,
    isResponding,
    workingTree,
    treeMetadata,
    generatedTree,
    isGenerating,
    error,
    startSession,
    sendMessage,
    generateTree,
    importToEditor,
    abandonSession,
    resumeSession,
  } = useAIChatStore()

  // Start or resume session on mount
  useEffect(() => {
    const resumeId = searchParams.get('session')
    if (resumeId && !sessionId) {
      resumeSession(resumeId)
    } else if (!sessionId && status === 'idle') {
      startSession(flowType)
    }
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  // Store sessionId in URL for resume support
  useEffect(() => {
    if (sessionId && !searchParams.get('session')) {
      setSearchParams((prev) => {
        const next = new URLSearchParams(prev)
        next.set('session', sessionId)
        return next
      }, { replace: true })
    }
  }, [sessionId, searchParams, setSearchParams])

  const handleSendMessage = useCallback(
    (content: string) => {
      sendMessage(content)
    },
    [sendMessage]
  )

  const [isSaving, setIsSaving] = useState(false)

  const handleGenerate = useCallback(() => {
    generateTree()
  }, [generateTree])

  const handleSave = useCallback(async () => {
    if (isSaving) return
    setIsSaving(true)
    try {
      const treeId = await importToEditor({
        name: treeMetadata?.name,
        description: treeMetadata?.description,
        tags: treeMetadata?.tags,
      })
      const path = getTreeEditorPath(treeId, flowType)
      navigate(path)
      toast.success('Flow saved to library')
    } catch {
      toast.error('Failed to save flow')
    } finally {
      setIsSaving(false)
    }
  }, [isSaving, importToEditor, treeMetadata, flowType, navigate])

  const handleReset = useCallback(async () => {
    await abandonSession()
    // Clear session from URL
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev)
      next.delete('session')
      return next
    }, { replace: true })
    startSession(flowType)
  }, [abandonSession, startSession, flowType, setSearchParams])

  // Show error toast
  useEffect(() => {
    if (error) {
      toast.error(error)
    }
  }, [error])

  if (status === 'idle' && !sessionId) {
    return (
      <div className="flex h-full items-center justify-center">
        <Spinner />
      </div>
    )
  }

  const previewTree = (generatedTree || workingTree) as TreeStructure | null

  return (
    <div className="flex h-full flex-col">
      <ChatToolbar
        currentPhase={currentPhase}
        status={status}
        isGenerating={isGenerating}
        hasGeneratedTree={!!generatedTree}
        isSaving={isSaving}
        onGenerate={handleGenerate}
        onSave={handleSave}
        onReset={handleReset}
      />

      <div className="flex flex-1 overflow-hidden">
        {/* Left panel: Chat (60%) */}
        <div className="flex w-3/5 flex-col border-r border-border max-lg:w-full">
          <ChatPanel
            messages={messages}
            isResponding={isResponding}
            onSendMessage={handleSendMessage}
            disabled={status !== 'active'}
          />
        </div>

        {/* Right panel: Tree preview (40%) — hidden below 1024px */}
        <div className="w-2/5 overflow-hidden bg-background max-lg:hidden">
          {previewTree ? (
            <StaticTreePreview
              tree={previewTree}
              name={treeMetadata?.name}
            />
          ) : (
            <EmptyPreview />
          )}
        </div>
      </div>
    </div>
  )
}

export default AIChatBuilderPage
