'use client';

import { useMemo } from 'react';
import { ChevronDown } from 'lucide-react';

import { MenuBuilder, type MenuItem } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';

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

/** One selectable model. */
export interface ComposerModelOption {
  /** Stable id — also the radio value. */
  id: string;
  /** Pill text + menu row label. */
  label: string;
  /** Secondary muted line in the menu. */
  description?: string;
  disabled?: boolean;
}

export interface ComposerModelPickerProps {
  /** Selected model id. */
  value: string;
  options: ComposerModelOption[];
  onChange: (id: string) => void;
  /** Omit to inherit the composer's size. */
  size?: ComposerSize;
  disabled?: boolean;
  /** Accessible label for the trigger. */
  label?: string;
  className?: string;
}

/** Per-size geometry for the trigger pill. */
const PILL_SIZE: Record<ComposerSize, { pill: string; text: string }> = {
  sm: { pill: 'h-7 gap-1 px-2', text: 'text-xs' },
  md: { pill: 'h-9 gap-1 px-2.5', text: 'text-sm' },
  lg: { pill: 'h-11 gap-1.5 px-3', text: 'text-sm' },
};

/**
 * A "Flash-Lite ▾" pill that opens a radio-group model picker — Gemini's
 * model switcher. Drop it into `composerSlots.inlineEnd` (trailing
 * cluster, before mic/send).
 */
export function ComposerModelPicker({
  value,
  options,
  onChange,
  size,
  disabled,
  label = 'Select model',
  className,
}: ComposerModelPickerProps) {
  const sz = PILL_SIZE[useResolvedComposerSize(size)];
  const current = options.find((o) => o.id === value);

  const items: MenuItem[] = useMemo(
    () => [
      {
        kind: 'radio-group',
        id: 'model',
        value,
        onValueChange: onChange,
        options: options.map((o) => ({
          id: o.id,
          value: o.id,
          label: o.label,
          description: o.description,
          disabled: o.disabled,
        })),
      },
    ],
    [value, options, onChange],
  );

  return (
    <MenuBuilder items={items} side="top" align="end">
      <button
        type="button"
        disabled={disabled}
        aria-label={label}
        title={label}
        className={cn(
          'inline-flex shrink-0 cursor-pointer items-center rounded-full',
          'text-muted-foreground transition-colors',
          'hover:bg-accent hover:text-accent-foreground',
          'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
          'disabled:pointer-events-none disabled:opacity-50',
          'data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
          '[&_svg]:size-4 [&_svg]:shrink-0',
          sz.pill,
          sz.text,
          className,
        )}
      >
        <span className="font-medium">{current?.label ?? value}</span>
        <ChevronDown aria-hidden className="opacity-70" />
      </button>
    </MenuBuilder>
  );
}
