'use client'

import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import { useState, useTransition } from 'react'

import { Button, Input } from '@/components/ui/controls'
import { useI18n } from '@/components/providers/i18n-provider'

/**
 * Switch the asset a page is analysing.
 *
 * It writes the code into the query string rather than holding it in component state, so
 * the analysis stays server-rendered and the URL a presenter lands on is the URL they
 * can share, bookmark or reload mid-demo.
 */
export function AssetPicker({ current, label }: { current: string; label?: string }) {
  const { t } = useI18n()
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()
  const [value, setValue] = useState(current)
  const [pending, startTransition] = useTransition()

  const submit = () => {
    const next = value.trim().toUpperCase()
    if (!next || next === current) return
    const query = new URLSearchParams(params.toString())
    query.set('asset', next)
    startTransition(() => router.push(`${pathname}?${query.toString()}`))
  }

  return (
    <div className="flex flex-wrap items-end gap-2">
      <div>
        <label htmlFor="asset-picker" className="block text-[10px] font-medium text-text-faint">
          {label ?? t('aiOps.focusAsset')}
        </label>
        <Input
          id="asset-picker"
          value={value}
          onChange={(event) => setValue(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter') submit()
          }}
          className="mt-1 h-8 w-32 font-mono text-xs"
          aria-label={label ?? t('aiOps.focusAsset')}
        />
      </div>
      <Button size="sm" onClick={submit} loading={pending}>
        {t('aiOps.changeAsset')}
      </Button>
    </div>
  )
}
