"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import {
  PageHeader,
  type PageHeaderCollaborator,
  type PageHeaderVariant,
} from "@/components/page-header"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  Shortcut,
} from "@/components/ui/dropdown-menu"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { Tip } from "@/components/ui/tip"
import { useAltKeyLabel, useModKeyLabel } from "@/hooks/use-mod-key-label"
import { COLLABORATION_HEADER_ADD_LABEL } from "@/lib/collaborator-access"
import { splitLibraryCourseFolderTitle } from "@/lib/library-nav"
import { LIBRARY_HEADER_COLLABORATORS } from "@/lib/mock/library-header-collaborators"

export interface LibraryPageHeaderProps {
  /** Scoped hub title (All / My / folder name) — keep in sync with `SiteHeader`. */
  title: string
  questionCount: number
  onNewQuestion: () => void
  onExport: () => void
  /** Omitted on surfaces without a metric strip (e.g. dedicated search). */
  showMetrics?: boolean
  onToggleMetrics?: () => void
  /** `collaboration` adds access line + collaborator face row before CTAs. */
  variant?: PageHeaderVariant
  /** Optional role / access row when `variant="collaboration"` (badge + copy). */
  accessInfo?: React.ReactNode
  collaborators?: PageHeaderCollaborator[]
  collaboratorDisplayLimit?: number
  onAddCollaborator?: () => void
  onCollaboratorsOpen?: () => void
  /** Empty-roster header CTA — default **Add collaborator**. */
  collaborationAddLabel?: string
  addCollaboratorLabel?: string
  /** Replaces the default “N questions · Last updated…” subtitle when set. */
  subtitleOverride?: string
  /** Dedicated search omits the primary New question CTA. */
  surface?: "hub" | "dedicated-search"
  /**
   * When provided, the **More** menu includes **Customize folder** (opens the hub folder sheet).
   * Wire this when the library is scoped to a folder (`?scope=folder&folderId=…`).
   */
  onCustomizeFolder?: () => void
}

export function LibraryPageHeader({
  title,
  questionCount,
  onNewQuestion,
  onExport,
  showMetrics,
  onToggleMetrics,
  variant = "default",
  accessInfo,
  collaborators = LIBRARY_HEADER_COLLABORATORS,
  collaboratorDisplayLimit = 3,
  onAddCollaborator = () => {},
  onCollaboratorsOpen,
  collaborationAddLabel = COLLABORATION_HEADER_ADD_LABEL,
  addCollaboratorLabel = "Invite people",
  subtitleOverride,
  surface = "hub",
  onCustomizeFolder,
}: LibraryPageHeaderProps) {
  const [moreOpen, setMoreOpen] = React.useState(false)
  const mod = useModKeyLabel()
  const alt = useAltKeyLabel()
  const newShortcut = `${mod}${alt}N`
  const exportShortcut = `${mod}${alt}E`
  const moreShortcut = `${mod}${alt}M`
  const metricsShortcut = `${mod}${alt}H`
  const { courseCode, title: displayTitle } = splitLibraryCourseFolderTitle(title)
  const countLine =
    subtitleOverride ??
    `${questionCount} ${questionCount === 1 ? "question" : "questions"} · Last updated now`
  const displaySubtitle = courseCode ? `${courseCode} · ${countLine}` : countLine
  const resolvedAccess = variant === "collaboration" ? accessInfo : undefined
  const showNewQuestion = surface === "hub"

  return (
    <PageHeader
      title={displayTitle}
      subtitle={displaySubtitle}
      variant={variant}
      accessInfo={resolvedAccess}
      collaborators={variant === "collaboration" ? collaborators : undefined}
      collaboratorDisplayLimit={collaboratorDisplayLimit}
      onCollaboratorsOpen={onCollaboratorsOpen ?? onAddCollaborator}
      addCollaboratorLabel={collaborationAddLabel}
      actions={
        <div className="flex items-center gap-2" role="group" aria-label="Library actions">
          {showNewQuestion ? (
            <>
              <Button
                type="button"
                size="lg"
                aria-keyshortcuts={newShortcut}
                onClick={onNewQuestion}
              >
                <i className="fa-light fa-plus" aria-hidden="true" />
                New question
                <KbdGroup className="ms-1.5">
                  <Kbd variant="bare">{newShortcut}</Kbd>
                </KbdGroup>
              </Button>
              <Shortcut keys={newShortcut} onInvoke={onNewQuestion} />
            </>
          ) : null}
          <DropdownMenu open={moreOpen} onOpenChange={setMoreOpen}>
            <Tip
              side="bottom"
              label={
                <span className="flex items-center gap-1.5">
                  More actions
                  <Kbd>{moreShortcut}</Kbd>
                </span>
              }
            >
              <DropdownMenuTrigger asChild>
                <Button
                  type="button"
                  size="icon-lg"
                  variant="outline"
                  aria-label="More actions"
                  aria-keyshortcuts={moreShortcut}
                >
                  <i className="fa-light fa-ellipsis text-base" aria-hidden="true" />
                </Button>
              </DropdownMenuTrigger>
            </Tip>
            <DropdownMenuContent align="end">
              {variant === "collaboration" ? (
                <DropdownMenuItem
                  onSelect={() => {
                    window.setTimeout(() => onAddCollaborator(), 0)
                  }}
                >
                  <i className="fa-light fa-user-plus" aria-hidden="true" />
                  {addCollaboratorLabel}
                </DropdownMenuItem>
              ) : null}
              {onCustomizeFolder ? (
                <DropdownMenuItem
                  onSelect={() => {
                    window.setTimeout(() => onCustomizeFolder(), 0)
                  }}
                >
                  <i className="fa-light fa-wand-magic-sparkles" aria-hidden="true" />
                  Customize folder
                </DropdownMenuItem>
              ) : null}
              <DropdownMenuItem
                shortcut={exportShortcut}
                onSelect={() => {
                  window.setTimeout(() => onExport(), 0)
                }}
              >
                <i className="fa-light fa-arrow-down-to-line" aria-hidden="true" />
                Export
              </DropdownMenuItem>
              {onToggleMetrics != null ? (
                <DropdownMenuItem
                  shortcut={metricsShortcut}
                  onSelect={() => {
                    window.setTimeout(() => onToggleMetrics(), 0)
                  }}
                >
                  <i
                    className={`fa-light ${(showMetrics ?? false) ? "fa-eye-slash" : "fa-eye"}`}
                    aria-hidden="true"
                  />
                  {(showMetrics ?? false) ? "Hide metric section" : "Show metric section"}
                </DropdownMenuItem>
              ) : null}
            </DropdownMenuContent>
          </DropdownMenu>
          <Shortcut
            keys={moreShortcut}
            onInvoke={() => setMoreOpen(open => !open)}
          />
          <Shortcut keys={exportShortcut} onInvoke={onExport} />
          {onToggleMetrics != null ? (
            <Shortcut keys={metricsShortcut} onInvoke={onToggleMetrics} />
          ) : null}
        </div>
      }
    />
  )
}
