"use client"

import { cn } from "@/lib/utils"
import { useIsXs } from "@/hooks/use-xs"
import { Icon, addCollection } from "@iconify/react"
import { icons as mdiIcons } from "@iconify-json/mdi"
import { SidebarCreateDialogs } from "@/components/gmail/sidebar/sidebar-create-dialogs"
import { SidebarHeader } from "@/components/gmail/sidebar/sidebar-header"
import { SidebarNavPanel } from "@/components/gmail/sidebar/sidebar-nav-panel"
import {
  useSidebarState,
  type SidebarProps,
} from "@/components/gmail/sidebar/use-sidebar-state"

addCollection(mdiIcons)

export function Sidebar(props: SidebarProps) {
  const { splitView = false, folderUnreadCounts = {}, selectedFolder, onSelectFolder } =
    props
  const isXs = useIsXs()
  const state = useSidebarState(props)

  return (
    <aside
      ref={state.sidebarRef}
      data-sidebar
      data-sidebar-overlay={state.isOverlayOpen ? "" : undefined}
      onMouseEnter={state.handleMouseEnter}
      onMouseLeave={state.handleMouseLeave}
      className={cn(
        "absolute left-0 top-0 bottom-0 z-40 flex flex-col overflow-x-hidden transition-[width,transform] duration-200 ease-linear select-none",
        state.panelSurfaceClass,
        state.isExpanded ? "w-60" : "w-[68px]",
        splitView && "border-r border-gray-200",
        !state.touchNav && state.hoverExpanded && "shadow-xl border-r border-gray-200 mail-sidebar-hover-frosted",
        state.isOverlayOpen && "z-50 shadow-xl border-r border-gray-200",
        props.collapsed && isXs && "-translate-x-full pointer-events-none"
      )}
    >
      <SidebarHeader
        splitView={splitView}
        isExpanded={state.isExpanded}
        panelSurfaceClass={state.panelSurfaceClass}
        splitViewLogoHeaderClass={state.splitViewLogoHeaderClass}
        splitViewLogoIconClass={state.splitViewLogoIconClass}
        touchNav={state.touchNav}
      />

      <SidebarNavPanel
        selectedFolder={selectedFolder}
        onSelectFolder={onSelectFolder}
        folderUnreadCounts={folderUnreadCounts}
        splitView={splitView}
        state={state}
      />

      <SidebarCreateDialogs
        folderDialogOpen={state.folderDialogOpen}
        setFolderDialogOpen={state.setFolderDialogOpen}
        labelDialogOpen={state.labelDialogOpen}
        setLabelDialogOpen={state.setLabelDialogOpen}
        newFolderName={state.newFolderName}
        setNewFolderName={state.setNewFolderName}
        newFolderParent={state.newFolderParent}
        setNewFolderParent={state.setNewFolderParent}
        newLabelName={state.newLabelName}
        setNewLabelName={state.setNewLabelName}
        newFolderNameInputRef={state.newFolderNameInputRef}
        newLabelNameInputRef={state.newLabelNameInputRef}
        folderParentOptions={state.folderParentOptions}
        onSubmitNewFolder={state.handleSubmitNewFolder}
        onSubmitNewLabel={state.handleSubmitNewLabel}
      />
    </aside>
  )
}

export type { SidebarProps }
