"use client";

import { useState } from "react";

type ChipOption<T extends number | string> = {
  id: T;
  label: string;
};

type MultiSelectChipsProps<T extends number | string> = {
  options: ChipOption<T>[];
  selected: T[];
  onToggle: (id: T) => void;
  size?: "sm" | "md";
  /** When set, chips start collapsed showing just selected count + names */
  collapsible?: boolean;
  /** Max selected labels to show in collapsed summary before truncating */
  collapsedMax?: number;
};

export default function MultiSelectChips<T extends number | string>({
  options,
  selected,
  onToggle,
  size = "sm",
  collapsible = false,
  collapsedMax = 3,
}: MultiSelectChipsProps<T>) {
  const [expanded, setExpanded] = useState(!collapsible);
  const btnSize = size === "sm" ? "btn-sm" : "";

  if (!expanded) {
    const selectedLabels = selected
      .map((id) => options.find((o) => o.id === id)?.label)
      .filter(Boolean) as string[];
    const shown = selectedLabels.slice(0, collapsedMax);
    const extra = selectedLabels.length - shown.length;
    const summary = shown.length
      ? shown.join(", ") + (extra > 0 ? ` +${extra}` : "")
      : "None";

    return (
      <button
        type="button"
        className="btn btn-sm btn-outline-secondary w-100 text-start d-flex justify-content-between align-items-center"
        onClick={() => setExpanded(true)}
      >
        <span className="text-truncate">{summary}</span>
        <span className="badge text-bg-primary rounded-pill ms-2">{selected.length}</span>
      </button>
    );
  }

  return (
    <div>
      <div className="d-flex flex-wrap gap-1">
        {options.map((option) => {
          const active = selected.includes(option.id);
          return (
            <button
              key={String(option.id)}
              type="button"
              className={`btn ${btnSize} ${active ? "btn-primary" : "btn-outline-secondary"}`}
              onClick={() => onToggle(option.id)}
            >
              {option.label}
            </button>
          );
        })}
      </div>
      {collapsible && (
        <button
          type="button"
          className="btn btn-link btn-sm p-0 mt-1 text-secondary"
          onClick={() => setExpanded(false)}
        >
          Collapse
        </button>
      )}
    </div>
  );
}
