"use client"

/**
 * Library **Folders** tree — shared outline primitives (`OutlineTree*`) so the rail
 * matches `HubTreePanelView` and shadcn sidebar file-tree rhythm.
 */

import * as React from "react"
import { Link } from "@/lib/next-compat"
import { Collapsible, CollapsibleTrigger } from "@/components/ui/collapsible"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tip } from "@/components/ui/tip"
import { cn } from "@/lib/utils"
import {
  OutlineTreeCollapsibleContentRail,
  OutlineTreeMenuItem,
  OutlineTreeSub,
} from "@/components/data-views/outline-tree-menu"
import type { LibraryFolder } from "@/lib/mock/library-folders"
import { LIBRARY_FOLDER_ICON_COLORS } from "@/lib/mock/library-folders"
import {
  isLibraryNavActive,
  libraryHubScopeHref,
  type LibraryNavState,
} from "@/lib/library-nav"

export interface LibraryFolderTreeBranchProps {
  folder: LibraryFolder
  folders: LibraryFolder[]
  pathname: string
  hubSearchParams: URLSearchParams
  nav: LibraryNavState
  canManageFolders: boolean
  canManageAccess: boolean
  onAddSubfolder: (parentId: string) => void
  onCustomizeFolder: (folder: LibraryFolder) => void
  onManageAccess: () => void
  onDeleteFolder: (folder: LibraryFolder) => void
}

export function LibraryFolderTreeBranch({
  folder,
  folders,
  pathname,
  hubSearchParams,
  nav,
  canManageFolders,
  canManageAccess,
  onAddSubfolder,
  onCustomizeFolder,
  onManageAccess,
  onDeleteFolder,
}: LibraryFolderTreeBranchProps) {
  const childFolders = React.useMemo(
    () =>
      folders
        .filter(f => f.parentId === folder.id)
        .sort((a, b) => a.name.localeCompare(b.name)),
    [folders, folder.id],
  )

  const hasSubfolders = childFolders.length > 0
  const isRootFolder = folder.parentId === null

  const folderHref = libraryHubScopeHref(pathname, hubSearchParams, {
    scope: "folder",
    folderId: folder.id,
  })
  const folderActive = isLibraryNavActive(pathname, nav, "folder", folder.id)

  return (
    <Collapsible defaultOpen={isRootFolder} className="group/collapsible">
      <div
        className={cn(
          "group/row flex min-w-0 items-center rounded-md px-2 transition-colors",
          folderActive
            ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground ring-1 ring-inset ring-sidebar-border/80"
            : "text-sidebar-foreground hover:bg-sidebar-accent/50",
        )}
      >
        {hasSubfolders ? (
          <CollapsibleTrigger asChild>
            <button
              type="button"
              className="flex size-8 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              aria-label={`${folder.name} — expand or collapse`}
            >
              <i
                className="fa-light fa-chevron-right text-xs transition-transform duration-150 group-data-[state=open]/collapsible:rotate-90"
                aria-hidden
              />
            </button>
          </CollapsibleTrigger>
        ) : (
          <div className="size-8 shrink-0" aria-hidden />
        )}
        <Tip label={folder.name} side="right">
          <Link
            href={folderHref}
            scroll={false}
            aria-current={folderActive ? "page" : undefined}
            className={cn(
              "flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm transition-colors",
              "rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
              !folderActive && "text-sidebar-foreground",
            )}
          >
            <i
              className={cn(
                "fa-light inline-flex size-4 shrink-0 items-center justify-center text-sm leading-none",
                folder.icon,
                LIBRARY_FOLDER_ICON_COLORS[folder.colorKey],
              )}
              aria-hidden
            />
            <span className="min-w-0 flex-1 truncate leading-tight">{folder.name}</span>
            {hasSubfolders ? (
              <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{childFolders.length}</span>
            ) : null}
          </Link>
        </Tip>
        {canManageFolders ? (
          <DropdownMenu>
            <Tip label={`Folder actions for ${folder.name}`} side="right">
              <DropdownMenuTrigger asChild>
                <Button
                  type="button"
                  size="icon-xs"
                  variant="ghost"
                  aria-label={`Folder actions for ${folder.name}`}
                  className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/row:opacity-100 group-focus-within/row:opacity-100"
                  onClick={event => event.stopPropagation()}
                >
                  <i className="fa-light fa-ellipsis text-xs" aria-hidden="true" />
                </Button>
              </DropdownMenuTrigger>
            </Tip>
            <DropdownMenuContent align="end">
              <DropdownMenuItem
                onSelect={() => {
                  window.setTimeout(() => onAddSubfolder(folder.id), 0)
                }}
              >
                <i className="fa-light fa-plus text-xs" aria-hidden="true" />
                Add folder
              </DropdownMenuItem>
              <DropdownMenuItem
                onSelect={() => {
                  window.setTimeout(() => onCustomizeFolder(folder), 0)
                }}
              >
                <i className="fa-light fa-wand-magic-sparkles text-xs" aria-hidden="true" />
                Customize
              </DropdownMenuItem>
              <DropdownMenuItem
                disabled={!canManageAccess}
                onSelect={() => {
                  window.setTimeout(() => onManageAccess(), 0)
                }}
              >
                <i className="fa-light fa-user-gear text-xs" aria-hidden="true" />
                Manage access
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                variant="destructive"
                onSelect={() => {
                  window.setTimeout(() => onDeleteFolder(folder), 0)
                }}
              >
                <i className="fa-light fa-trash text-xs" aria-hidden="true" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ) : null}
      </div>
      {hasSubfolders ? (
        <OutlineTreeCollapsibleContentRail>
          <OutlineTreeSub surface="sidebar" guideLayout="chevronRail">
            {childFolders.map(child => (
              <OutlineTreeMenuItem key={child.id}>
                <LibraryFolderTreeBranch
                  folder={child}
                  folders={folders}
                  pathname={pathname}
                  hubSearchParams={hubSearchParams}
                  nav={nav}
                  canManageFolders={canManageFolders}
                  canManageAccess={canManageAccess}
                  onAddSubfolder={onAddSubfolder}
                  onCustomizeFolder={onCustomizeFolder}
                  onManageAccess={onManageAccess}
                  onDeleteFolder={onDeleteFolder}
                />
              </OutlineTreeMenuItem>
            ))}
          </OutlineTreeSub>
        </OutlineTreeCollapsibleContentRail>
      ) : null}
    </Collapsible>
  )
}
