import type { LucideIcon } from "lucide-react"
import {
  Inbox,
  Star,
  Clock,
  Send,
  FileText,
  ClockArrowUp,
  ShieldAlert,
  Trash2,
  User,
} from "lucide-react"
import {
  folderTreeNavIconNameClosed,
  navFolderIconColorFromBgClass,
} from "@/lib/folder-nav-icons"
import type { FolderTreeNode } from "@/lib/sidebar-nav-maps"
import type { LabelRowItem } from "@/lib/sidebar-nav-data"
import { defaultNavLabelRowsSnapshot, labelRowById } from "@/lib/sidebar-nav-data"
import { findFolderPath } from "@/lib/sidebar-nav-folder-ids"
import { parseMailNavVisitKey } from "@/lib/mail-folder-display"
import { normalizeInboxTabSegment } from "@/lib/mail-url"

const SYSTEM_ICONS: Record<string, LucideIcon> = {
  inbox: Inbox,
  starred: Star,
  snoozed: Clock,
  sent: Send,
  drafts: FileText,
  scheduled: ClockArrowUp,
  spam: ShieldAlert,
  trash: Trash2,
}

export type MailNavIcon =
  | { kind: "lucide"; Icon: LucideIcon }
  | { kind: "folder"; icon: string; color: string }
  | { kind: "iconify"; icon: string }

export function resolveMailNavIcon(
  visitKey: string,
  folderTree: FolderTreeNode[],
  labelRows: readonly LabelRowItem[] = defaultNavLabelRowsSnapshot
): MailNavIcon {
  const { folderId, inboxTab } = parseMailNavVisitKey(visitKey)

  if (folderId === "inbox") {
    const tab = normalizeInboxTabSegment(inboxTab ?? "primary")
    if (tab === "primary") return { kind: "lucide", Icon: User }
    if (tab === "all") return { kind: "lucide", Icon: Inbox }
    const row = labelRowById(labelRows, tab)
    if (row?.icon) return { kind: "iconify", icon: row.icon }
    return { kind: "lucide", Icon: Inbox }
  }

  if (folderId === "important") {
    return { kind: "iconify", icon: "mdi:label-variant-outline" }
  }

  const system = SYSTEM_ICONS[folderId]
  if (system) return { kind: "lucide", Icon: system }

  const navRow = labelRowById(labelRows, folderId)
  if (navRow?.icon) return { kind: "iconify", icon: navRow.icon }

  const path = findFolderPath(folderTree, folderId)
  if (path?.length) {
    const leaf = path[path.length - 1]!
    return {
      kind: "folder",
      icon: folderTreeNavIconNameClosed(!!leaf.children?.length),
      color: navFolderIconColorFromBgClass(leaf.color ?? "bg-slate-400"),
    }
  }

  return {
    kind: "folder",
    icon: folderTreeNavIconNameClosed(false),
    color: navFolderIconColorFromBgClass("bg-slate-400"),
  }
}
