'use client'

import React, { useState, createContext, useContext } from 'react'
import { cn } from '@/lib/utils'
import { CaretDown } from '@phosphor-icons/react'
import * as PhosphorIcons from '@phosphor-icons/react'

/**
 * Accordion Components for MDX Documentation
 * 
 * Mintlify-compatible accordion components for collapsible content sections.
 */

// Dynamic icon resolver
function getIcon(iconName: string): React.ComponentType<{ className?: string; weight?: string }> | null {
  if (!iconName) return null
  
  const pascalCase = iconName
    .split(/[-_]/)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join('')
  
  const Icon = (PhosphorIcons as Record<string, unknown>)[pascalCase] as React.ComponentType<{ className?: string; weight?: string }> | undefined
  return Icon || null
}

// Context for AccordionGroup
interface AccordionGroupContextType {
  openItems: Set<string>
  toggleItem: (id: string) => void
  allowMultiple: boolean
}

const AccordionGroupContext = createContext<AccordionGroupContextType | null>(null)

interface AccordionProps {
  title: string
  children: React.ReactNode
  description?: string
  icon?: string
  iconType?: string
  defaultOpen?: boolean
  className?: string
}

export function Accordion({
  title,
  children,
  description,
  icon,
  defaultOpen = false,
  className,
}: AccordionProps) {
  const groupContext = useContext(AccordionGroupContext)
  const [localOpen, setLocalOpen] = useState(defaultOpen)
  
  // Generate a stable ID for this accordion
  const id = React.useId()
  
  // Use group context if available, otherwise use local state
  const isOpen = groupContext ? groupContext.openItems.has(id) : localOpen
  const toggle = () => {
    if (groupContext) {
      groupContext.toggleItem(id)
    } else {
      setLocalOpen(!localOpen)
    }
  }
  
  // Register default open state with group on mount
  React.useEffect(() => {
    if (groupContext && defaultOpen) {
      groupContext.toggleItem(id)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  
  const Icon = icon ? getIcon(icon) : null
  
  return (
    <div
      className={cn(
        'border border-border rounded-lg overflow-hidden',
        'bg-card',
        className
      )}
    >
      <button
        type="button"
        onClick={toggle}
        className={cn(
          'flex w-full items-center gap-3 p-4 text-left',
          'hover:bg-muted/50 transition-colors',
          'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50'
        )}
        aria-expanded={isOpen}
      >
        {Icon && (
          <Icon className="h-5 w-5 shrink-0 text-primary" weight="duotone" />
        )}
        
        <div className="flex-1 min-w-0">
          <div className="font-medium text-foreground">{title}</div>
          {description && (
            <div className="text-sm text-muted-foreground mt-0.5">{description}</div>
          )}
        </div>
        
        <CaretDown
          className={cn(
            'h-5 w-5 shrink-0 text-muted-foreground transition-transform duration-200',
            isOpen && 'rotate-180'
          )}
          weight="bold"
        />
      </button>
      
      <div
        className={cn(
          'grid transition-all duration-200 ease-in-out',
          isOpen ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'
        )}
      >
        <div className="overflow-hidden">
          <div className="px-4 pb-4 text-sm text-foreground/90 [&>p]:mb-2 [&>p:last-child]:mb-0">
            {children}
          </div>
        </div>
      </div>
    </div>
  )
}

interface AccordionGroupProps {
  children: React.ReactNode
  allowMultiple?: boolean
  className?: string
}

export function AccordionGroup({
  children,
  allowMultiple = true,
  className,
}: AccordionGroupProps) {
  const [openItems, setOpenItems] = useState<Set<string>>(new Set())
  
  const toggleItem = (id: string) => {
    setOpenItems(prev => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        if (!allowMultiple) {
          next.clear()
        }
        next.add(id)
      }
      return next
    })
  }
  
  return (
    <AccordionGroupContext.Provider value={{ openItems, toggleItem, allowMultiple }}>
      <div className={cn('space-y-2 my-4', className)}>
        {children}
      </div>
    </AccordionGroupContext.Provider>
  )
}
