"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

/**
 * SegmentedControl — pill-shaped filter row with optional inline count badges.
 *
 * Different from Tabs: this is a single filter bar with no content panel below.
 * Used to replace ad-hoc filter-chip rows (bills inbox, annual-report prefill,
 * etc.) with a single primitive.
 *
 * Usage:
 *   <SegmentedControl value={filter} onValueChange={setFilter}>
 *     <SegmentedControlItem value="all">
 *       All <SegmentedCount>{12}</SegmentedCount>
 *     </SegmentedControlItem>
 *     <SegmentedControlItem value="unscheduled" count={3}>
 *       Unscheduled
 *     </SegmentedControlItem>
 *   </SegmentedControl>
 *
 * The active item gets bg-background + shadow on top of the muted track.
 */

type SegmentedControlContextValue = {
  value: string;
  setValue: (v: string) => void;
};

const SegmentedControlCtx = React.createContext<SegmentedControlContextValue | null>(null);

function useSegmentedControlContext() {
  const ctx = React.useContext(SegmentedControlCtx);
  if (!ctx)
    throw new Error("SegmentedControl primitives must be used inside <SegmentedControl>");
  return ctx;
}

export function SegmentedControl({
  value,
  defaultValue,
  onValueChange,
  className,
  children,
  "aria-label": ariaLabel,
}: {
  value?: string;
  defaultValue?: string;
  onValueChange?: (v: string) => void;
  className?: string;
  children: React.ReactNode;
  "aria-label"?: string;
}) {
  const [internal, setInternal] = React.useState(defaultValue ?? "");
  const isControlled = value !== undefined;
  const current = isControlled ? (value as string) : internal;
  const setValue = React.useCallback(
    (v: string) => {
      if (!isControlled) setInternal(v);
      onValueChange?.(v);
    },
    [isControlled, onValueChange],
  );
  const ctxValue = React.useMemo<SegmentedControlContextValue>(
    () => ({ value: current, setValue }),
    [current, setValue],
  );
  return (
    <SegmentedControlCtx.Provider value={ctxValue}>
      <div
        role="tablist"
        aria-label={ariaLabel}
        className={cn(
          "inline-flex items-center gap-1 rounded-full bg-muted p-1",
          className,
        )}
      >
        {children}
      </div>
    </SegmentedControlCtx.Provider>
  );
}

export function SegmentedControlItem({
  value,
  count,
  disabled,
  className,
  children,
}: {
  value: string;
  count?: number;
  disabled?: boolean;
  className?: string;
  children: React.ReactNode;
}) {
  const { value: current, setValue } = useSegmentedControlContext();
  const active = current === value;
  return (
    <button
      type="button"
      role="tab"
      aria-selected={active}
      disabled={disabled}
      onClick={() => setValue(value)}
      className={cn(
        "inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium transition-colors",
        "disabled:pointer-events-none disabled:opacity-50",
        active
          ? "bg-background text-foreground shadow-sm"
          : "text-muted-foreground hover:text-foreground",
        className,
      )}
    >
      {children}
      {count !== undefined && <SegmentedCount>{count}</SegmentedCount>}
    </button>
  );
}

export function SegmentedCount({
  children,
  className,
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <span
      className={cn("text-[10px] tabular-nums opacity-70", className)}
      aria-hidden="true"
    >
      {children}
    </span>
  );
}
