import type { LucideIcon } from "lucide-react"
import {
  Inbox,
  Star,
  Clock,
  Tag,
  Send,
  FileText,
  ClockArrowUp,
  ShieldAlert,
  Trash2,
  Folder,
  Users,
  Info,
  MessageSquare,
} from "lucide-react"
import type { FolderTreeNode } from "@/lib/sidebar-nav-maps"
import { findFolderPath } from "@/lib/sidebar-nav-folder-ids"
import { parseMailNavVisitKey } from "@/lib/mail-folder-display"

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

const INBOX_TAB_ICONS: Record<string, LucideIcon> = {
  primary: Inbox,
  promotions: Tag,
  social: Users,
  updates: Info,
  forums: MessageSquare,
}

export type MailNavIcon =
  | { kind: "lucide"; Icon: LucideIcon }
  | { kind: "folder-dot"; colorClass: string }

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

  if (folderId === "inbox") {
    const tab = inboxTab ?? "primary"
    return { kind: "lucide", Icon: INBOX_TAB_ICONS[tab] ?? Inbox }
  }

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

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

  return { kind: "lucide", Icon: Folder }
}
