'use client'

import { useMemo, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X, Spinner } from '@phosphor-icons/react'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import type { BrainfishCollection, BrainfishRESTRequest, BrainfishDocPage } from '@/lib/api-docs/types'
import { CollectionTree } from './collection-tree'
import { SidebarSection } from './sidebar-section'
import { SidebarItem, SlidingIndicatorProvider } from './sidebar-item'
import { SidebarGroup } from './sidebar-group'
import { useMobile } from '@/lib/api-docs/mobile-context'
import { cn } from '@/lib/utils'

interface ApiVersion {
  version: string
  spec: string
  default: boolean
}

interface ApiDocsSidebarProps {
  collection: BrainfishCollection
  selectedRequest: BrainfishRESTRequest | null
  selectedDocSection: string | null
  selectedDocPage?: string | null
  activeTab?: string
  onSelectRequest: (request: BrainfishRESTRequest) => void
  onSelectDocumentation?: (headingId: string) => void
  onSelectDocPage?: (slug: string) => void
  apiVersions?: ApiVersion[]
  selectedApiVersion?: string | null
  onApiVersionChange?: (version: string) => void
  isVersionLoading?: boolean
}

export function DocsSidebar({
  collection,
  selectedRequest,
  selectedDocSection,
  selectedDocPage,
  activeTab,
  onSelectRequest,
  onSelectDocumentation,
  onSelectDocPage,
  apiVersions,
  selectedApiVersion,
  onApiVersionChange,
  isVersionLoading,
}: ApiDocsSidebarProps) {
  const { isMobile, isLeftSidebarOpen, closeLeftSidebar } = useMobile()
  const [mounted, setMounted] = useState(false)
  
  // Ensure we're mounted before using portal (for SSR)
  useEffect(() => {
    setMounted(true)
  }, [])
  
  // Handle request selection with mobile close
  const handleSelectRequest = (request: BrainfishRESTRequest) => {
    onSelectRequest(request)
    if (isMobile) {
      closeLeftSidebar()
    }
  }
  
  // Handle doc click with mobile close
  const handleDocClickWithClose = (headingId: string) => {
    if (onSelectDocumentation) {
      onSelectDocumentation(headingId)
    }
    if (isMobile) {
      closeLeftSidebar()
    }
  }
  
  // Handle doc page click with mobile close
  const handleDocPageClick = (slug: string) => {
    if (onSelectDocPage) {
      onSelectDocPage(slug)
    }
    if (isMobile) {
      closeLeftSidebar()
    }
  }
  
  // Get doc groups from collection
  const docGroups = collection.docGroups || []
  
  // Check if any child in a group is selected
  const isChildSelected = (page: BrainfishDocPage): boolean => {
    if (!page.children) return false
    return page.children.some(child => selectedDocPage === child.slug)
  }
  
  // Get the selected child slug for a group (for triggering auto-expand)
  const getSelectedChildSlug = (page: BrainfishDocPage): string | null => {
    if (!page.children) return null
    const selected = page.children.find(child => selectedDocPage === child.slug)
    return selected?.slug || null
  }
  
  // Render a doc page item (may be a collapsible group with children)
  const renderDocPage = (page: BrainfishDocPage) => {
    // Handle collapsible group with children
    if (page.isGroup && page.children && page.children.length > 0) {
      return (
        <SidebarGroup
          key={page.id}
          title={page.title}
          defaultOpen={isChildSelected(page)}
          selectedChildSlug={getSelectedChildSlug(page)}
        >
          {page.children.map(child => {
            const isSelected = selectedDocPage === child.slug
            return (
              <SidebarItem
                key={child.id}
                itemId={`doc-${child.slug}`}
                selected={isSelected}
                indent={1}
                icon={child.icon}
                onClick={() => handleDocPageClick(child.slug)}
              >
                {child.title}
              </SidebarItem>
            )
          })}
        </SidebarGroup>
      )
    }
    
    // Regular page item
    const isSelected = selectedDocPage === page.slug
    
    return (
      <SidebarItem
        key={page.id}
        itemId={`doc-${page.slug}`}
        selected={isSelected}
        icon={page.icon}
        onClick={() => handleDocPageClick(page.slug)}
      >
        {page.title}
      </SidebarItem>
    )
  }

  // Sidebar content component (shared between mobile and desktop)
  const sidebarContent = (
    <>
      {/* Mobile close button */}
      {isMobile && (
        <div className="px-4 h-[41px] flex items-center justify-end border-b border-sidebar-border shrink-0">
          <Button
            variant="ghost"
            size="icon"
            onClick={closeLeftSidebar}
            className="h-7 w-7 lg:hidden"
          >
            <X className="h-4 w-4" weight="bold" />
          </Button>
        </div>
      )}

      {/* API Version Selector - Only show when multiple versions exist and on API Reference tab */}
      {activeTab === 'api-reference' && apiVersions && apiVersions.length > 1 && (
        <div className="docs-sidebar-version-selector px-4 py-3 border-b border-sidebar-border shrink-0">
          <div className="flex items-center justify-between mb-1.5">
            <label className="docs-sidebar-version-label text-xs font-medium text-muted-foreground">
              API Version
            </label>
            {isVersionLoading && (
              <Spinner className="h-3 w-3 animate-spin text-muted-foreground" />
            )}
          </div>
          <Select
            value={selectedApiVersion || apiVersions.find(v => v.default)?.version || apiVersions[0]?.version}
            onValueChange={(value) => onApiVersionChange?.(value)}
            disabled={isVersionLoading}
          >
            <SelectTrigger className={cn("docs-sidebar-version-trigger w-full h-9 text-sm", isVersionLoading && "opacity-50")}>
              <SelectValue placeholder="Select version" />
            </SelectTrigger>
            <SelectContent>
              {apiVersions.map((v) => (
                <SelectItem key={v.version} value={v.version}>
                  {v.version}
                  {v.default && <span className="ml-2 text-xs text-muted-foreground">(latest)</span>}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Scrollable content with sliding indicator */}
      <SlidingIndicatorProvider className="docs-sidebar-content flex-1 overflow-y-auto overflow-x-hidden custom-scroll">
        {/* Documentation Pages Section (from docs.json groups) */}
        {docGroups.length > 0 && (
          <>
            {docGroups.map((group, index) => (
              <SidebarSection 
                key={group.id} 
                title={group.title}
                icon={group.icon}
                className={index > 0 ? '' : ''}
              >
                {group.pages.map(renderDocPage)}
              </SidebarSection>
            ))}
          </>
        )}

        {/* Endpoints Section */}
        {(collection.folders.length > 0 || collection.requests.length > 0) && (
          <SidebarSection 
            title="Endpoints" 
            className={docGroups.length > 0 ? 'border-t border-sidebar-border' : ''}
          >
            <CollectionTree
              collection={collection}
              selectedRequest={selectedRequest}
              onSelectRequest={handleSelectRequest}
            />
          </SidebarSection>
        )}
      </SlidingIndicatorProvider>
    </>
  )

  // Mobile sidebar rendered via portal to escape stacking context
  const mobileSidebar = mounted && isMobile ? createPortal(
    <>
      {/* Mobile overlay backdrop */}
      {isLeftSidebarOpen && (
        <div 
          className="docs-sidebar-overlay fixed inset-0 bg-black/50 z-[55] lg:hidden"
          onClick={closeLeftSidebar}
        />
      )}
      
      <aside 
        className={cn(
          "docs-sidebar flex flex-col border-r border-sidebar-border overflow-hidden bg-muted dark:bg-background",
          "fixed inset-y-0 left-0 z-[60] w-[280px] h-full",
          "transform transition-transform duration-300 ease-in-out",
          !isLeftSidebarOpen && "-translate-x-full",
          isLeftSidebarOpen && "translate-x-0"
        )}
      >
        {sidebarContent}
      </aside>
    </>,
    document.body
  ) : null

  // Desktop sidebar rendered in place
  const desktopSidebar = !isMobile ? (
    <aside 
      className={cn(
        "docs-sidebar flex flex-col border-r border-sidebar-border overflow-hidden bg-muted dark:bg-background",
        "relative w-72 h-full"
      )}
    >
      {sidebarContent}
    </aside>
  ) : null

  return (
    <>
      {mobileSidebar}
      {desktopSidebar}
    </>
  )
}
