import { createContext, useContext, useState, useCallback, useMemo, ReactNode } from 'react'
import { LucideIcon } from 'lucide-react'

export interface BreadcrumbItem {
  label: string
  path?: string
  icon?: LucideIcon
}

interface BreadcrumbContextType {
  breadcrumbs: BreadcrumbItem[]
  setBreadcrumbs: (items: BreadcrumbItem[]) => void
  appendBreadcrumb: (item: BreadcrumbItem) => void
  updateLastBreadcrumb: (label: string) => void
  popBreadcrumb: () => void
}

const BreadcrumbContext = createContext<BreadcrumbContextType | undefined>(undefined)

export function BreadcrumbProvider({ children }: { children: ReactNode }) {
  const [breadcrumbs, setBreadcrumbsState] = useState<BreadcrumbItem[]>([])

  const setBreadcrumbs = useCallback((items: BreadcrumbItem[]) => {
    setBreadcrumbsState(items)
  }, [])

  const appendBreadcrumb = useCallback((item: BreadcrumbItem) => {
    setBreadcrumbsState(prev => [...prev, item])
  }, [])

  const updateLastBreadcrumb = useCallback((label: string) => {
    setBreadcrumbsState(prev => {
      if (prev.length === 0) return prev
      const updated = [...prev]
      updated[updated.length - 1] = { ...updated[updated.length - 1], label }
      return updated
    })
  }, [])

  const popBreadcrumb = useCallback(() => {
    setBreadcrumbsState(prev => prev.slice(0, -1))
  }, [])

  const value = useMemo(() => ({
    breadcrumbs,
    setBreadcrumbs,
    appendBreadcrumb,
    updateLastBreadcrumb,
    popBreadcrumb
  }), [breadcrumbs, setBreadcrumbs, appendBreadcrumb, updateLastBreadcrumb, popBreadcrumb])

  return (
    <BreadcrumbContext.Provider value={value}>
      {children}
    </BreadcrumbContext.Provider>
  )
}

export function useBreadcrumbContext() {
  const context = useContext(BreadcrumbContext)
  if (context === undefined) {
    throw new Error('useBreadcrumbContext must be used within a BreadcrumbProvider')
  }
  return context
}
