'use client'

import { AlertTriangle, Loader2, RefreshCw } from 'lucide-react'
import { useId } from 'react'
import { CapabilityBadges } from './CapabilityBadges.js'
import type { AiModelView } from './useAiSettings.js'

const INPUT_CLASS =
  'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60'
const LABEL_CLASS = 'mb-1 flex items-center gap-2 text-sm font-medium text-foreground'

function priceLabel(model: AiModelView): string | null {
  const p = model.pricing
  if (!p) return null
  if (typeof p.inputPerMillion === 'number' && typeof p.outputPerMillion === 'number') {
    return `$${p.inputPerMillion}/$${p.outputPerMillion} per 1M tokens`
  }
  if (typeof p.inputPerMillion === 'number') return `$${p.inputPerMillion} per 1M tokens`
  if (typeof p.image === 'number') return `$${p.image} per image`
  return null
}

export function ModelSelector({
  models,
  value,
  onChange,
  onRefresh,
  refreshing,
  disabled,
  noModelsHint,
}: {
  models: AiModelView[]
  value: string
  onChange: (id: string) => void
  onRefresh: () => void
  refreshing: boolean
  disabled: boolean
  /** Shown when there are no models to choose from. */
  noModelsHint?: string
}) {
  const selectId = useId()
  const selected = models.find((m) => m.id === value || m.providerModelId === value)
  // The configured model is no longer in the catalog — keep the choice, warn.
  const selectedUnavailable = Boolean(value) && !selected
  const price = selected ? priceLabel(selected) : null

  return (
    <div>
      <label htmlFor={selectId} className={LABEL_CLASS}>
        Default model
      </label>
      <div className="flex items-center gap-2">
        <select
          id={selectId}
          value={value}
          disabled={disabled}
          onChange={(e) => onChange(e.target.value)}
          className={INPUT_CLASS}
        >
          <option value="">Select a model…</option>
          {selectedUnavailable && <option value={value}>{value} (unavailable)</option>}
          {models.map((m) => (
            <option key={m.id} value={m.id} disabled={m.status === 'unavailable'}>
              {m.displayName}
              {m.status === 'deprecated' ? ' (deprecated)' : ''}
              {m.status === 'unavailable' ? ' (unavailable)' : ''}
            </option>
          ))}
        </select>
        <button
          type="button"
          onClick={onRefresh}
          disabled={disabled || refreshing}
          aria-label="Refresh models"
          className="border-border text-foreground hover:bg-accent inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-60"
        >
          {refreshing ? (
            <Loader2 size={16} className="animate-spin" aria-hidden="true" />
          ) : (
            <RefreshCw size={16} aria-hidden="true" />
          )}
          <span className="sr-only sm:not-sr-only">Refresh models</span>
        </button>
      </div>

      {models.length === 0 && (
        <p className="text-muted-foreground mt-1 text-sm">
          {noModelsHint ?? 'No models available yet. Connect a provider and refresh.'}
        </p>
      )}

      {selectedUnavailable && (
        <p className="text-warning mt-2 flex items-start gap-1.5 text-sm" role="status">
          <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
          The selected model is no longer offered by the provider. Pick another or refresh the list.
        </p>
      )}

      {selected && (
        <div className="mt-2 space-y-1.5">
          <CapabilityBadges capabilities={selected.capabilities} />
          <div className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">
            {typeof selected.contextWindow === 'number' && (
              <span>{selected.contextWindow.toLocaleString()} token context</span>
            )}
            {price && <span>{price}</span>}
            {selected.status === 'deprecated' && (
              <span className="text-warning">Deprecated by provider</span>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
