'use client'

import { useEffect, useState, useCallback } from 'react'
import Image from 'next/image'
import { X, ArrowClockwise } from '@phosphor-icons/react'
import type { BrainfishCollection, BrainfishRESTRequest } from '@/lib/api-docs/types'
import type { PrefillData } from '@/lib/api-docs/agent/types'
import type { DebugContext } from '../playground/response-viewer'
import { AgentChat } from '../agent'
import { Button } from '@/components/ui/button'
import { useMobile } from '@/lib/api-docs/mobile-context'
import { cn } from '@/lib/utils'
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip'

interface RightSidebarProps {
  /** Current endpoint - when null, only agent mode is available */
  request: BrainfishRESTRequest | null
  /** Full collection for agent context */
  collection: BrainfishCollection
  /** Pre-generated API summary (cached server-side) */
  apiSummary?: string | null
  /** Callback when agent navigates to an endpoint */
  onNavigateToEndpoint: (endpointId: string) => void
  /** Callback when agent prefills parameters */
  onPrefillParameters: (data: PrefillData) => void
  /** Debug context from playground response - triggers agent debug */
  debugContext?: DebugContext | null
  /** Callback to clear debug context after processing */
  onClearDebugContext?: () => void
  /** Explain context from playground response - triggers agent explanation */
  explainContext?: DebugContext | null
  /** Callback to clear explain context after processing */
  onClearExplainContext?: () => void
  /** Callback to open global auth dialog */
  onOpenGlobalAuth?: () => void
  /** Callback to navigate to authorization tab in playground */
  onNavigateToAuthTab?: () => void
  /** Callback to navigate to parameters tab in playground */
  onNavigateToParamsTab?: () => void
  /** Callback to navigate to body tab in playground */
  onNavigateToBodyTab?: () => void
  /** Callback to navigate to headers tab in playground */
  onNavigateToHeadersTab?: () => void
  /** Callback to navigate to a documentation section */
  onNavigateToDocSection?: (sectionId: string) => void
  /** Callback to navigate to a documentation page */
  onNavigateToDocPage?: (slug: string) => void
}

export function RightSidebar({ 
  request, 
  collection,
  apiSummary,
  onNavigateToEndpoint,
  onPrefillParameters,
  debugContext,
  onClearDebugContext,
  explainContext,
  onClearExplainContext,
  onOpenGlobalAuth,
  onNavigateToAuthTab,
  onNavigateToParamsTab,
  onNavigateToBodyTab,
  onNavigateToHeadersTab,
  onNavigateToDocSection,
  onNavigateToDocPage,
}: RightSidebarProps) {
  // Mobile context
  const { isMobile, isRightSidebarOpen, closeRightSidebar } = useMobile()
  
  // Debug context to send to agent (full context for card display)
  const [pendingDebugContext, setPendingDebugContext] = useState<DebugContext | null>(null)

  // Handle debug context
  useEffect(() => {
    if (debugContext) {
      // Pass full context to agent
      setPendingDebugContext(debugContext)
      
      // Clear the debug context from parent
      onClearDebugContext?.()
    }
  }, [debugContext, onClearDebugContext])
  
  // Clear debug context after it's been used
  const handleDebugContextConsumed = () => {
    setPendingDebugContext(null)
  }

  // Key for resetting chat
  const [chatKey, setChatKey] = useState(0)
  
  // Track if there are messages
  const [hasMessages, setHasMessages] = useState(false)
  
  // Handle reset conversation
  const handleResetConversation = useCallback(() => {
    // Clear chat storage before remounting
    localStorage.removeItem('brainfish-agent-chat')
    setChatKey(prev => prev + 1)
    setHasMessages(false)
  }, [])

  return (
    <>
      {/* Mobile overlay backdrop - z-[55] to cover header (z-50) but below panel (z-60) */}
      {isMobile && isRightSidebarOpen && (
        <div 
          className="docs-agent-overlay fixed inset-0 bg-black/50 z-[55] lg:hidden"
          onClick={closeRightSidebar}
        />
      )}
      
      <div 
        className={cn(
          "docs-agent-panel border-l border-border bg-background flex flex-col overflow-hidden",
          // Desktop: always visible, fixed width
          "lg:relative lg:w-96 lg:h-full lg:z-auto",
          // Mobile: drawer behavior from right - z-[60] to appear above header (z-50)
          "fixed inset-y-0 right-0 z-[60] w-[320px] sm:w-[360px] h-full",
          "transform transition-transform duration-300 ease-in-out",
          "lg:transform-none lg:translate-x-0",
          isMobile && !isRightSidebarOpen && "translate-x-full",
          isMobile && isRightSidebarOpen && "translate-x-0"
        )}
      >
        {/* Header */}
        <div className="docs-agent-header shrink-0 px-3 sm:px-4 h-[41px] flex items-center border-b border-border bg-muted/30">
          <div className="flex items-center justify-between gap-2 w-full">
            {/* Left: Assistant */}
            <div className="docs-agent-title flex items-center gap-2.5">
              <div className="docs-agent-avatar size-7 rounded-full overflow-hidden bg-muted flex items-center justify-center shrink-0">
                <Image src="/icon.png" alt="Assistant" width={28} height={28} className="size-7 object-cover" />
              </div>
              <span className="text-sm font-medium">Assistant</span>
            </div>
            
            {/* Right: Actions */}
            <div className="flex items-center gap-1 shrink-0">
              {/* Reset conversation button - only show when there are messages */}
              {hasMessages && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleResetConversation}
                      className="h-7 w-7 text-muted-foreground hover:text-foreground"
                    >
                      <ArrowClockwise className="h-4 w-4" weight="bold" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="bottom">New conversation</TooltipContent>
                </Tooltip>
              )}
              
              {/* Mobile close button */}
              {isMobile && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={closeRightSidebar}
                  className="h-7 w-7 lg:hidden"
                >
                  <X className="h-4 w-4" weight="bold" />
                </Button>
              )}
            </div>
          </div>
        </div>
        
        {/* Content */}
        <div className="docs-agent-content flex-1 overflow-hidden">
          <AgentChat 
            key={chatKey}
            collection={collection}
            currentEndpoint={request}
            apiSummary={apiSummary}
            onNavigate={onNavigateToEndpoint}
            onPrefill={onPrefillParameters}
            debugContext={pendingDebugContext}
            onDebugContextConsumed={handleDebugContextConsumed}
            explainContext={explainContext}
            onExplainContextConsumed={onClearExplainContext}
            onOpenGlobalAuth={onOpenGlobalAuth}
            onNavigateToAuthTab={onNavigateToAuthTab}
            onNavigateToParamsTab={onNavigateToParamsTab}
            onNavigateToBodyTab={onNavigateToBodyTab}
            onNavigateToHeadersTab={onNavigateToHeadersTab}
            onNavigateToDocSection={onNavigateToDocSection}
            onNavigateToDocPage={onNavigateToDocPage}
            onHasMessagesChange={setHasMessages}
          />
        </div>
      </div>
    </>
  )
}
