"use client"

import { useMemo } from "react"
import { toast } from "sonner"
import { BreadcrumbNav } from "@/components/drive/breadcrumb-nav"
import { DriveBulkToolbar } from "@/components/drive/drive-bulk-toolbar"
import { DriveFilterBar } from "@/components/drive/drive-filter-bar"
import { DriveSortMenu } from "@/components/drive/drive-sort-menu"
import { DriveViewModeToggle } from "@/components/drive/drive-view-mode-toggle"
import { DriveSearchBreadcrumb } from "@/components/drive/drive-search-breadcrumb"
import type { DriveFileInfo } from "@/lib/api/types"
import type { DriveSearchState } from "@/lib/drive/drive-search"
import type { DriveView } from "@/lib/drive/drive-url"
import { DRIVE_CARD_PAD_X, DRIVE_FILTER_CONTENT_GAP } from "@/lib/drive/drive-chrome-classes"
import { useDriveMutations } from "@/lib/api/hooks/use-drive-queries"
import { useDriveUIStore } from "@/lib/stores/drive-ui-store"
import { cn } from "@/lib/utils"

const VIEW_TITLES: Partial<Record<DriveView, string>> = {
  recent: "Récents",
  starred: "Favoris",
  trash: "Corbeille",
  org: "Dossier d'organisation",
  mount: "Volume monté",
}

export function DriveBrowserChrome({
  view,
  segments,
  rootId,
  isTrash,
  items,
  searchState,
}: {
  view: DriveView
  segments: string[]
  rootId?: string | null
  isTrash?: boolean
  items: DriveFileInfo[]
  searchState?: DriveSearchState | null
}) {
  const selectedPaths = useDriveUIStore((s) => s.selectedPaths)
  const clearSelection = useDriveUIStore((s) => s.clearSelection)
  const mutations = useDriveMutations()
  const selectedTargets = useMemo(
    () => items.filter((f) => selectedPaths.has(f.path)),
    [items, selectedPaths]
  )
  const showBulk = selectedTargets.length > 0
  const showBreadcrumb = view === "files" || view === "shared" || view === "org" || view === "mount"
  const showSearchBreadcrumb = view === "search" && searchState
  const title = VIEW_TITLES[view]
  const allowShare = view !== "shared"
  const showEmptyTrash = view === "trash" && !showBulk && items.length > 0

  const onEmptyTrash = async () => {
    if (!window.confirm("Vider la corbeille ? Cette action est irréversible.")) return
    try {
      await mutations.emptyTrash.mutateAsync()
      clearSelection()
      toast.success("Corbeille vidée")
    } catch {
      toast.error("Impossible de vider la corbeille")
    }
  }

  return (
    <div className={cn("shrink-0", DRIVE_FILTER_CONTENT_GAP)}>
      <div className={cn("flex min-h-12 shrink-0 items-center justify-between gap-4 py-1", DRIVE_CARD_PAD_X)}>
        <div className="min-w-0 flex-1">
          {showSearchBreadcrumb ? (
            <DriveSearchBreadcrumb search={searchState} />
          ) : showBreadcrumb ? (
            <BreadcrumbNav
              view={view}
              segments={segments}
              rootId={rootId}
              writable={view === "files" || view === "org" || view === "mount"}
            />
          ) : title ? (
            <div className="flex min-w-0 items-center gap-3">
              <p className="text-[1.375rem] font-normal leading-snug tracking-tight text-[#202124] dark:text-foreground">
                {title}
              </p>
              {showEmptyTrash ? (
                <button
                  type="button"
                  className="shrink-0 text-sm font-medium text-[#1a73e8] hover:underline dark:text-[#8ab4f8]"
                  onClick={() => void onEmptyTrash()}
                  disabled={mutations.emptyTrash.isPending}
                >
                  Vider la corbeille
                </button>
              ) : null}
            </div>
          ) : null}
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <DriveSortMenu />
          <DriveViewModeToggle />
        </div>
      </div>
      {showBulk ? (
        <DriveBulkToolbar
          targets={selectedTargets}
          isTrash={isTrash}
          allowShare={allowShare}
        />
      ) : (
        <DriveFilterBar showContacts={view !== "trash"} />
      )}
    </div>
  )
}
