"use client"

import { memo } from "react"
import { Icon } from "@iconify/react"
import type { InboxCategoryTabIcon } from "@/lib/inbox-category-tabs"
import { navFolderIconColorFromBgClass } from "@/lib/label-pill-contrast"
import { cn } from "@/lib/utils"

const DEFAULT_ICON_CLASS = "size-4 shrink-0"

type MailInboxCategoryTabIconsProps = {
  tabs: readonly InboxCategoryTabIcon[]
  onTabClick?: (tabId: string) => void
  className?: string
  iconClassName?: string
}

export const MailInboxCategoryTabIcons = memo(function MailInboxCategoryTabIcons({
  tabs,
  onTabClick,
  className,
  iconClassName = DEFAULT_ICON_CLASS,
}: MailInboxCategoryTabIconsProps) {
  if (tabs.length === 0) return null

  const ariaLabel = tabs.map((t) => t.label).join(", ")

  return (
    <span
      className={cn("inline-flex shrink-0 items-center gap-0.5", className)}
      aria-label={`Catégories : ${ariaLabel}`}
    >
      {tabs.map((tab) => {
        const color = navFolderIconColorFromBgClass(tab.badgeColor)
        const icon = (
          <Icon
            icon={tab.icon}
            className={iconClassName}
            style={{ color }}
            aria-hidden
          />
        )
        if (!onTabClick) {
          return (
            <span
              key={tab.id}
              title={tab.label}
              className="inline-flex items-center justify-center p-0.5"
            >
              {icon}
            </span>
          )
        }
        return (
          <button
            key={tab.id}
            type="button"
            title={tab.label}
            aria-label={tab.label}
            onClick={(e) => {
              e.stopPropagation()
              onTabClick(tab.id)
            }}
            className="inline-flex cursor-pointer items-center justify-center rounded-full p-0.5 hover:bg-black/6"
          >
            {icon}
          </button>
        )
      })}
    </span>
  )
})
