/**
 * BulkContactTagActions — the Contacts table's bulk "Tags" action. A single
 * checklist of the user's tags shows which are already on the selection
 * (checked = on all selected, indeterminate = on some); toggling adds to, or
 * removes from, every selected contact. A new tag can be created from the
 * search. Pure & controlled.
 */
import { type ReactElement, useState } from "react";
import { ChevronDownIcon, PlusIcon, SearchIcon, TagIcon } from "lucide-react";
import { Button } from "./button";
import { Checkbox } from "./checkbox";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";

export interface BulkTagOption {
  name: string;
  /** How many of the selected contacts already carry this tag. */
  onCount: number;
}

export interface BulkContactTagActionsProps {
  /** How many contacts are selected. */
  selectedCount: number;
  /** The tag library with per-selection counts. */
  options: BulkTagOption[];
  /** Add a tag to every selected contact. */
  onAdd: (name: string) => void;
  /** Remove a tag from every selected contact. */
  onRemove: (name: string) => void;
  /** Allow creating a new tag from the search. Defaults to true. */
  allowCreate?: boolean;
}

const norm = (s: string): string => s.trim().toLowerCase();

export function BulkContactTagActions({
  selectedCount,
  options,
  onAdd,
  onRemove,
  allowCreate = true,
}: BulkContactTagActionsProps): ReactElement {
  const [query, setQuery] = useState("");

  const filtered = options.filter((o) => norm(o.name).includes(norm(query)));
  const trimmed = query.trim();
  const canCreate =
    allowCreate &&
    trimmed.length > 0 &&
    !options.some((o) => norm(o.name) === norm(trimmed));

  return (
    <Popover>
      <PopoverTrigger
        render={<Button variant="outline" size="sm" className="gap-1.5" />}
      >
        <TagIcon aria-hidden="true" className="size-4" />
        Tags
        <ChevronDownIcon aria-hidden="true" className="size-4" />
      </PopoverTrigger>
      <PopoverContent align="end" className="w-72 p-0">
        <div className="border-b border-border px-3 py-2">
          <p className="text-caption text-muted-foreground">
            Apply to {selectedCount} selected contact
            {selectedCount === 1 ? "" : "s"}
          </p>
        </div>
        <div className="flex items-center gap-2 border-b border-border px-3">
          <SearchIcon className="size-4 shrink-0 text-muted-foreground" />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search or create a tag…"
            aria-label="Search or create a tag"
            className="h-9 w-full bg-transparent text-body-small outline-none placeholder:text-muted-foreground"
          />
        </div>
        <ul className="max-h-64 overflow-y-auto p-1">
          {filtered.map((o) => {
            const all = o.onCount === selectedCount && selectedCount > 0;
            const some = o.onCount > 0 && o.onCount < selectedCount;
            return (
              <li
                key={o.name}
                className="flex items-center gap-2 px-2 py-1.5 text-body-small"
              >
                <Checkbox
                  id={`bulk-tag-${o.name}`}
                  aria-label={o.name}
                  checked={all}
                  indeterminate={some}
                  onCheckedChange={() =>
                    all ? onRemove(o.name) : onAdd(o.name)
                  }
                />
                <label
                  htmlFor={`bulk-tag-${o.name}`}
                  className="flex-1 cursor-pointer truncate"
                >
                  {o.name}
                </label>
                {some ? (
                  <span className="text-caption tabular-nums text-muted-foreground">
                    {o.onCount}/{selectedCount}
                  </span>
                ) : null}
              </li>
            );
          })}
          {canCreate ? (
            <li>
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start gap-2 text-body-small font-normal"
                onClick={() => {
                  onAdd(trimmed);
                  setQuery("");
                }}
              >
                <PlusIcon className="size-4" />
                Create &amp; add{" "}
                <span className="font-medium text-foreground">
                  &ldquo;{trimmed}&rdquo;
                </span>
              </Button>
            </li>
          ) : null}
          {filtered.length === 0 && !canCreate ? (
            <li className="px-2 py-6 text-center text-body-small text-muted-foreground">
              No tags
            </li>
          ) : null}
        </ul>
      </PopoverContent>
    </Popover>
  );
}

export default BulkContactTagActions;
