import { Bell, ChevronDown } from 'lucide-react';

import { Fragment, type ReactNode, useState } from 'react';

export type BannerPriority = 'connection' | 'billing' | 'setup' | 'nudge';

const PRIORITY_ORDER: Record<BannerPriority, number> = {
  connection: 4,
  billing: 3,
  setup: 2,
  nudge: 1,
};

export interface BannerEntry {
  key: string;
  priority: BannerPriority;
  render: () => ReactNode;
}

interface BannerStackProps {
  banners: BannerEntry[];
  visibleCount?: number;
}

export function BannerStack({ banners, visibleCount = 2 }: BannerStackProps) {
  const [expanded, setExpanded] = useState(false);

  if (banners.length === 0) return null;

  const sorted = [...banners].sort(
    (a, b) => PRIORITY_ORDER[b.priority] - PRIORITY_ORDER[a.priority],
  );

  const visible = expanded ? sorted : sorted.slice(0, visibleCount);
  const hiddenCount = Math.max(0, sorted.length - visibleCount);
  const showExpander = !expanded && hiddenCount > 0;

  return (
    <div>
      {visible.map((banner) => (
        <Fragment key={banner.key}>{banner.render()}</Fragment>
      ))}
      {showExpander && (
        <button
          type="button"
          onClick={() => setExpanded(true)}
          aria-expanded={false}
          className="mb-8 flex w-full items-center justify-center gap-2 rounded-md border border-dashed border-border bg-muted/30 px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
        >
          <Bell className="h-3.5 w-3.5" aria-hidden="true" />
          {hiddenCount} more notification{hiddenCount === 1 ? '' : 's'}
          <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
        </button>
      )}
    </div>
  );
}
