'use client';

import type { ReactNode } from 'react';
import { X } from 'lucide-react';

import { cn } from '@djangocfg/ui-core/lib';

import { useResolvedComposerSize } from './size-context';
import type { ComposerSize } from './types';

export interface ComposerToolPillProps {
  /** Leading icon — a lucide-react element. */
  icon?: ReactNode;
  /** Pill text. */
  label: ReactNode;
  /** Accent fill when the tool/mode is active. */
  active?: boolean;
  /** Clicking the pill body (toggles the tool). */
  onClick?: () => void;
  /** When set, renders a trailing `×` that calls this instead. */
  onRemove?: () => void;
  disabled?: boolean;
  /** Omit to inherit the composer's size. */
  size?: ComposerSize;
  className?: string;
}

/** Per-size geometry — round capsule heights matching the action bar. */
const PILL_SIZE: Record<ComposerSize, { pill: string; text: string; icon: string }> = {
  sm: { pill: 'h-7 gap-1 px-2', text: 'text-xs', icon: '[&_svg]:size-3.5' },
  md: { pill: 'h-9 gap-1.5 px-3', text: 'text-sm', icon: '[&_svg]:size-4' },
  lg: { pill: 'h-11 gap-2 px-3.5', text: 'text-sm', icon: '[&_svg]:size-[1.125rem]' },
};

/**
 * A rounded action-bar capsule for a selected tool or mode — Gemini's
 * "🎨 Images" pill. Drop it into `composerSlots.inlineStart` (leading
 * cluster). When `onRemove` is set the pill shows a trailing `×`.
 */
export function ComposerToolPill({
  icon,
  label,
  active = false,
  onClick,
  onRemove,
  disabled,
  size,
  className,
}: ComposerToolPillProps) {
  const sz = PILL_SIZE[useResolvedComposerSize(size)];
  return (
    <div
      className={cn(
        'inline-flex shrink-0 items-center rounded-full border transition-colors',
        sz.pill,
        sz.text,
        sz.icon,
        active
          ? 'border-transparent bg-accent text-accent-foreground'
          : 'border-border bg-transparent text-muted-foreground',
        disabled && 'pointer-events-none opacity-50',
        className,
      )}
    >
      <button
        type="button"
        onClick={onClick}
        disabled={disabled}
        aria-pressed={onClick ? active : undefined}
        className={cn(
          'inline-flex items-center gap-1.5 outline-none',
          onClick && !disabled && 'cursor-pointer hover:text-foreground',
        )}
      >
        {icon ? <span className="flex shrink-0 [&_svg]:shrink-0">{icon}</span> : null}
        <span className="font-medium">{label}</span>
      </button>
      {onRemove ? (
        <button
          type="button"
          onClick={onRemove}
          disabled={disabled}
          aria-label="Remove"
          title="Remove"
          className={cn(
            '-mr-1 ml-0.5 inline-flex size-5 cursor-pointer items-center justify-center',
            'rounded-full transition-colors hover:bg-foreground/10 [&_svg]:size-3.5',
          )}
        >
          <X aria-hidden />
        </button>
      ) : null}
    </div>
  );
}
