import type { DriveFileInfo } from "@/lib/api/types"
import type { DriveFolderPlacement, DriveSortField } from "@/lib/stores/drive-settings-store"

function parseModified(iso: string): number {
  const d = new Date(iso)
  return Number.isNaN(d.getTime()) ? 0 : d.getTime()
}

function compareDriveFiles(
  a: DriveFileInfo,
  b: DriveFileInfo,
  field: DriveSortField,
  dir: "asc" | "desc"
): number {
  const mul = dir === "asc" ? 1 : -1
  if (field === "name") {
    return (
      mul *
      a.name.localeCompare(b.name, undefined, {
        sensitivity: "base",
        numeric: true,
      })
    )
  }
  if (field === "size") {
    return mul * (a.size - b.size)
  }
  return mul * (parseModified(a.last_modified) - parseModified(b.last_modified))
}

export function sortDriveItems(
  items: DriveFileInfo[],
  opts: {
    sortField: DriveSortField
    sortDir: "asc" | "desc"
    folderPlacement: DriveFolderPlacement
  }
): DriveFileInfo[] {
  const cmp = (a: DriveFileInfo, b: DriveFileInfo) =>
    compareDriveFiles(a, b, opts.sortField, opts.sortDir)

  if (opts.folderPlacement === "mixed") {
    return [...items].sort(cmp)
  }

  const folders = items.filter((f) => f.type === "directory").sort(cmp)
  const files = items.filter((f) => f.type !== "directory").sort(cmp)
  return [...folders, ...files]
}

export const DRIVE_SORT_FIELD_LABELS: Record<DriveSortField, string> = {
  name: "Nom",
  date: "Date de modification",
  size: "Taille",
}

export function driveSortOrderLabels(field: DriveSortField): {
  asc: string
  desc: string
} {
  if (field === "name") {
    return { asc: "De A à Z", desc: "De Z à A" }
  }
  if (field === "size") {
    return { asc: "Plus petit", desc: "Plus grand" }
  }
  return { asc: "Plus ancien", desc: "Plus récent" }
}
