'use client'

import { AlertTriangle } from 'lucide-react'
import { useId } from 'react'
import { SettingsCard, SettingsToggleRow } from './components.js'
import { capabilityLabel, effectiveFeatureModel, isModelCompatible } from './featureModel.js'
import type { AiFeatureView, AiModelView } from './useAiSettings.js'

const SELECT_CLASS =
  'w-full rounded-md border border-border bg-input-background px-3 py-2 text-sm text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60'

/**
 * Global AI feature toggles with per-feature model routing. Each switch persists
 * (via the Save bar) to the shared `ai.features.*` flags; the optional model
 * picker overrides which model that feature uses (otherwise it inherits the
 * default). Enforcement across modules lands in a later phase; here we surface
 * and store the operator's intent.
 */
export function AiFeaturesCard({
  features,
  models,
  defaultModelId,
  canEdit,
  onToggle,
  onSetFeatureModel,
}: {
  features: AiFeatureView[]
  models: AiModelView[]
  defaultModelId: string
  canEdit: boolean
  onToggle: (key: string, enabled: boolean) => void
  onSetFeatureModel: (key: string, modelId: string) => void
}) {
  return (
    <SettingsCard
      title="AI Features"
      description="Turn individual AI-powered features on or off, and optionally route each to a specific model."
    >
      {features.length === 0 ? (
        <p className="text-muted-foreground text-sm">No AI features are available.</p>
      ) : (
        <div className="divide-border divide-y">
          {features.map((f) => (
            <FeatureRow
              key={f.key}
              feature={f}
              models={models}
              defaultModelId={defaultModelId}
              canEdit={canEdit}
              onToggle={onToggle}
              onSetFeatureModel={onSetFeatureModel}
            />
          ))}
        </div>
      )}
    </SettingsCard>
  )
}

function FeatureRow({
  feature,
  models,
  defaultModelId,
  canEdit,
  onToggle,
  onSetFeatureModel,
}: {
  feature: AiFeatureView
  models: AiModelView[]
  defaultModelId: string
  canEdit: boolean
  onToggle: (key: string, enabled: boolean) => void
  onSetFeatureModel: (key: string, modelId: string) => void
}) {
  const selectId = useId()
  const required = feature.requiredCapabilities ?? []
  const effective = effectiveFeatureModel(feature.modelId, defaultModelId, required, models)
  const defaultModel = models.find(
    (m) => m.id === defaultModelId || m.providerModelId === defaultModelId,
  )

  const hasModels = models.length > 0
  const defaultLabel = defaultModel
    ? `Use default (${defaultModel.displayName})`
    : 'Use default model'

  return (
    <div className="py-4 first:pt-0 last:pb-0">
      <SettingsToggleRow
        label={feature.label}
        description={feature.description}
        checked={feature.enabled}
        disabled={!canEdit}
        onChange={(v) => onToggle(feature.key, v)}
      />

      {feature.enabled && (
        <div className="mt-3 pl-0">
          <label htmlFor={selectId} className="text-muted-foreground mb-1 block text-sm">
            Model
          </label>
          {hasModels ? (
            <select
              id={selectId}
              value={feature.modelId ?? ''}
              disabled={!canEdit}
              onChange={(e) => onSetFeatureModel(feature.key, e.target.value)}
              className={SELECT_CLASS}
            >
              <option value="">{defaultLabel}</option>
              {models.map((m) => {
                const compatible = isModelCompatible(m, required)
                return (
                  <option key={m.id} value={m.id} disabled={!compatible}>
                    {m.displayName}
                    {m.status === 'unavailable' ? ' (unavailable)' : ''}
                    {m.status !== 'unavailable' && !compatible ? ' (incompatible)' : ''}
                  </option>
                )
              })}
            </select>
          ) : (
            <p className="text-muted-foreground text-sm">
              Connect a provider and refresh models to route this feature.
            </p>
          )}

          {hasModels && !effective.isOverride && (
            <p className="text-muted-foreground mt-1 text-sm">
              {effective.model
                ? `Uses the default model (${effective.model.displayName}).`
                : 'No default model selected yet — set one in the AI Assistant card above.'}
            </p>
          )}

          {hasModels && effective.missingCapabilities.length > 0 && (
            <p className="text-warning mt-1.5 flex items-start gap-1.5 text-sm" role="status">
              <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
              This model can&apos;t do{' '}
              {effective.missingCapabilities.map(capabilityLabel).join(', ')}, which this feature
              needs. Pick a compatible model.
            </p>
          )}
        </div>
      )}
    </div>
  )
}
