"use client"

import type { ElementType } from "react"
import { Icon } from "@iconify/react"
import { cn, formatCount } from "@/lib/utils"
import { useEmailDropTarget } from "@/lib/drag-context"
import { navRowRoundedWhenActive } from "@/components/gmail/sidebar/sidebar-nav-primitives"

export function SidebarNavItem({
  item,
  isSelected,
  unreadCount,
  isExpanded,
  onSelectFolder,
}: {
  item: { id: string; label: string; icon: ElementType | string }
  isSelected: boolean
  unreadCount: number
  isExpanded: boolean
  onSelectFolder: (id: string) => void
}) {
    const { isOver, dropHandlers } = useEmailDropTarget(item.id, item.label)
    const hasUnread = unreadCount > 0
    const iconClassName = cn(
      "h-5 w-5 shrink-0",
      hasUnread && !isSelected && "text-gray-900"
    )
    return (
      <button
        onClick={() => onSelectFolder(item.id)}
        title={!isExpanded ? item.label : undefined}
        {...dropHandlers}
        className={cn(
          "flex h-8 w-full min-w-0 shrink-0 cursor-pointer items-center gap-4 pl-6 pr-3 transition-colors",
          navRowRoundedWhenActive(isSelected || isOver),
          isSelected
            ? "bg-mail-nav-selected text-mail-nav-selected font-medium"
            : isOver
              ? "bg-mail-nav-drop text-foreground"
              : hasUnread
                ? "text-gray-900 hover:bg-mail-nav-hover"
                : "text-gray-700 hover:bg-mail-nav-hover"
        )}
      >
        {typeof item.icon === "string" ? (
          <Icon icon={item.icon} className={iconClassName} aria-hidden />
        ) : (
          <item.icon className={iconClassName} />
        )}
        {isExpanded && (
          <div className="flex min-w-0 flex-1 items-baseline gap-4">
            <span
              className={cn(
                "min-w-0 flex-1 truncate text-left text-sm leading-5",
                hasUnread && !isSelected && "font-semibold text-gray-900"
              )}
            >
              {item.label}
            </span>
            {unreadCount > 0 && (
              <span
                className={cn(
                  "shrink-0 text-xs tabular-nums leading-none",
                  isSelected && "font-medium",
                  hasUnread && !isSelected && "font-semibold"
                )}
              >
                {formatCount(unreadCount)}
              </span>
            )}
          </div>
        )}
      </button>
    )
}
