"use client"

import * as React from "react"

import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/shared/components/ui/sheet"
import { cn } from "@/shared/lib/utils"

type SidebarContextType = {
  expanded: boolean
  setExpanded: (expanded: boolean) => void
  isMobile: boolean
  toggleSidebar: () => void
}

const SidebarContext = React.createContext<SidebarContextType | undefined>(
  undefined
)

export function useSidebar() {
  const context = React.useContext(SidebarContext)
  if (!context) {
    throw new Error("useSidebar must be used within a SidebarProvider")
  }
  return context
}

interface SidebarProviderProps {
  children: React.ReactNode
  sidebar: React.ReactNode
}

export function SidebarProvider({ children, sidebar }: SidebarProviderProps) {
  const [expanded, setExpanded] = React.useState(true)
  const [isMobile, setIsMobile] = React.useState(false)
  const [openMobile, setOpenMobile] = React.useState(false)

  React.useEffect(() => {
    const checkMobile = () => {
      const mobile = window.innerWidth < 768
      setIsMobile(mobile)
      if (mobile) {
        setExpanded(true)
      }
    }
    checkMobile()
    window.addEventListener("resize", checkMobile)
    return () => window.removeEventListener("resize", checkMobile)
  }, [])

  const toggleSidebar = () => {
    if (isMobile) {
      setOpenMobile(!openMobile)
    } else {
      setExpanded(!expanded)
    }
  }

  return (
    <SidebarContext.Provider
      value={{ expanded, setExpanded, isMobile, toggleSidebar }}
    >
      <div className="flex h-screen overflow-hidden w-full flex-col md:flex-row bg-background">
        {/* Mobile Trigger & Sheet */}
        {isMobile && (
          <Sheet open={openMobile} onOpenChange={setOpenMobile}>
            <SheetContent side="left" className="w-[80%] p-0 sm:w-[300px]">
              <SheetHeader className="sr-only">
                <SheetTitle>Navigation Menu</SheetTitle>
              </SheetHeader>
              <div className="h-full py-4">
                {sidebar}
              </div>
            </SheetContent>
          </Sheet>
        )}

        {/* Desktop Sidebar Wrapper */}
        {!isMobile && (
          <aside
            className={cn(
              "bg-sidebar border-sidebar-border text-sidebar-foreground sticky top-0 hidden h-screen flex-col border-r transition-[width] duration-300 ease-in-out md:flex",
              expanded ? "w-64" : "w-16"
            )}
          >
            {sidebar}
          </aside>
        )}

        {/* Main Content Wrapper - Right Side */}
        <div className="flex-1 flex flex-col min-w-0 transition-[margin] duration-300 ease-in-out h-screen overflow-hidden">
          {children}
        </div>
      </div>
    </SidebarContext.Provider>
  )
}
