'use client'

import { useCallback, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { KeyRound, Loader2, Shield, Trash2, CheckCircle2, XCircle, Zap, FlaskConical, Pencil, X } from 'lucide-react'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { cn } from '@/lib/utils'
import { providerDisplayName } from '@/lib/ai/provider-labels'
import { PROVIDER_MODEL_SUGGESTIONS } from '@/lib/ai/models-list'

function displayName(provider: string): string {
  return providerDisplayName(provider)
}

function providerHint(provider: string): string {
  const models = PROVIDER_MODEL_SUGGESTIONS[provider] ?? []
  return models.slice(0, 2).join(', ')
}

const MANUAL_MODEL_PROVIDERS = new Set(['custom'])
const NEEDS_BASE_URL = new Set(['custom', 'custom_openai', 'custom_anthropic'])

function getDefaultBaseUrl(p: string): string {
  if (p === 'custom_openai') return 'https://api.openai.com/v1'
  if (p === 'custom_anthropic') return 'https://api.anthropic.com/v1'
  return ''
}

// ─── Types ────────────────────────────────────────────────────────────────────
type SavedKey = {
  provider: string
  alias: string | null
  model: string | null
  baseUrl: string | null
  isActive: boolean
  lastUsedAt: string | null
}

async function loadKeys(): Promise<{ keys: SavedKey[]; allowedProviders: string[] }> {
  const res = await fetch('/api/user/api-keys')
  if (!res.ok) throw new Error('Failed to load')
  return res.json()
}

async function fetchModelsFromServer(provider: string, key?: string, baseUrl?: string): Promise<string[]> {
  const q = new URLSearchParams({ provider })
  if (key) q.set('key', key)
  if (baseUrl) q.set('baseUrl', baseUrl)
  const res = await fetch(`/api/user/api-keys/live-models?${q}`)
  if (!res.ok) return []
  const body = await res.json()
  return body.success && Array.isArray(body.models) ? body.models : []
}

// ─── Inline edit form for a saved key ────────────────────────────────────────
function EditKeyForm({
  savedKey,
  onDone,
  onInvalidate,
}: {
  savedKey: SavedKey
  onDone: () => void
  onInvalidate: () => void
}) {
  const [alias, setAlias] = useState(savedKey.alias ?? '')
  const [model, setModel] = useState(savedKey.model ?? '')
  const [baseUrl, setBaseUrl] = useState(savedKey.baseUrl ?? getDefaultBaseUrl(savedKey.provider))
  const [newKey, setNewKey] = useState('')  // empty = keep existing key
  const [models, setModels] = useState<string[]>([])
  const [loadingModels, setLoadingModels] = useState(false)
  const [testing, setTesting] = useState(false)
  const [testResult, setTestResult] = useState<{ ok: boolean; latency?: number; reply?: string; error?: string } | null>(null)

  const { t } = useLanguage()

  const needsUrl = NEEDS_BASE_URL.has(savedKey.provider)
  const manualModel = MANUAL_MODEL_PROVIDERS.has(savedKey.provider)

  // Load models on mount
  useState(() => {
    if (manualModel) return
    fetchModelsFromServer(savedKey.provider, undefined, baseUrl || undefined).then((list) => {
      setModels(list)
      if (list.length > 0 && !model) setModel(list[0])
    })
  })

  const saveMutation = useMutation({
    mutationFn: async () => {
      const payload: Record<string, string | undefined> = {
        model: model || undefined,
        alias: alias.trim() || undefined,
      }
      if (needsUrl) payload.baseUrl = baseUrl
      if (newKey.length >= 8) payload.apiKey = newKey
      const res = await fetch(`/api/user/api-keys/${encodeURIComponent(savedKey.provider)}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) throw new Error(body.message ?? body.error ?? t('common.error'))
    },
    onSuccess: () => {
      toast.success(t('byok.updated', { name: displayName(savedKey.provider) }))
      onInvalidate()
      onDone()
    },
    onError: (err: Error) => toast.error(err.message),
  })

  async function testModel() {
    const keyToUse = newKey.length >= 8 ? newKey : ''
    if (!keyToUse && !model) return
    if (!keyToUse) {
      toast.info(t('byok.testHint'))
      return
    }
    setTesting(true)
    setTestResult(null)
    try {
      const q = new URLSearchParams({ provider: savedKey.provider, key: keyToUse, model })
      if (needsUrl && baseUrl) q.append('baseUrl', baseUrl)
      const res = await fetch(`/api/user/api-keys/test-model?${q}`)
      setTestResult(await res.json())
    } catch {
      setTestResult({ ok: false, error: t('byok.contactError') })
    } finally {
      setTesting(false)
    }
  }

  const showModelDropdown = !manualModel && models.length > 0
  const showModelInput = manualModel || (!loadingModels && models.length === 0)

  return (
    <div className="mt-2 border border-brand-accent/20 rounded-xl bg-brand-accent/5 p-4 space-y-3">
      <p className="text-[13px] font-semibold uppercase tracking-wider text-brand-accent">
        {t('byok.editLabel', { name: displayName(savedKey.provider) })}
      </p>

      {/* Alias */}
      <div className="grid gap-3 sm:grid-cols-2">
        <div className="space-y-1">
          <Label htmlFor={`edit-alias-${savedKey.provider}`} className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.aliasLabel')}</Label>
          <Input id={`edit-alias-${savedKey.provider}`} value={alias} onChange={(e) => setAlias(e.target.value)} placeholder={t('byok.aliasPlaceholder')} />
        </div>
        {needsUrl && (
          <div className="space-y-1">
            <Label htmlFor={`edit-baseurl-${savedKey.provider}`} className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.apiUrl')}</Label>
            <Input id={`edit-baseurl-${savedKey.provider}`} value={baseUrl} onChange={(e) => setBaseUrl(e.target.value.trim())} placeholder="https://api.example.com/v1" />
          </div>
        )}
      </div>

      {/* Model */}
      <div className="space-y-1">
        <Label htmlFor={`edit-model-${savedKey.provider}`} className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.model')}</Label>
        {showModelDropdown ? (
          <Select value={model} onValueChange={setModel}>
            <SelectTrigger id={`edit-model-${savedKey.provider}`}><SelectValue placeholder={t('byok.choose')} /></SelectTrigger>
            <SelectContent>{models.map((m) => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
          </Select>
        ) : showModelInput ? (
          <Input id={`edit-model-${savedKey.provider}`} value={model} onChange={(e) => setModel(e.target.value)} placeholder="ex. MiniMax-M2.7" />
        ) : <div className="flex items-center gap-2 text-xs text-concrete py-1"><Loader2 className="h-3 w-3 animate-spin" />{t('common.loading')}</div>}
      </div>

      {/* Key rotation (optional) */}
      <div className="space-y-1">
        <Label htmlFor={`edit-key-${savedKey.provider}`} className="text-[13px] font-medium uppercase tracking-wider text-concrete">
          {t('byok.newKey')} <span className="normal-case font-normal text-concrete">{t('byok.newKeyHint')}</span>
        </Label>
        <Input
          id={`edit-key-${savedKey.provider}`}
          type="password"
          autoComplete="off"
          value={newKey}
          onChange={(e) => { setNewKey(e.target.value); setTestResult(null) }}
          placeholder={t('byok.keyPlaceholder')}
        />
      </div>

      {/* Test result */}
      {testResult && (
        <div className={cn(
          'flex items-start gap-2 rounded-lg px-3 py-2 text-[13px] border',
          testResult.ok ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-700 dark:text-emerald-400' : 'bg-rose-500/10 border-rose-500/20 text-rose-700 dark:text-rose-400'
        )}>
          {testResult.ok ? <CheckCircle2 size={12} className="shrink-0 mt-0.5" /> : <XCircle size={12} className="shrink-0 mt-0.5" />}
          <span>
            {testResult.ok
              ? `${t('byok.operational')}${testResult.latency ? ` (${testResult.latency}ms)` : ''}${testResult.reply ? ` · ${testResult.reply}` : ''}`
              : testResult.error ?? t('common.error')
            }
          </span>
        </div>
      )}

      {/* Actions */}
      <div className="flex gap-2 pt-1">
        <button
          type="button"
          disabled={!newKey || newKey.length < 8 || testing}
          onClick={testModel}
          className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-[13px] font-semibold uppercase tracking-[0.1em] border border-border bg-white dark:bg-white/5 hover:border-brand-accent/50 transition-colors disabled:opacity-40 disabled:pointer-events-none"
        >
          {testing ? <Loader2 size={11} className="animate-spin" /> : <FlaskConical size={11} />}
          {t('byok.test')}
        </button>
        <Button
          type="button"
          disabled={saveMutation.isPending}
          onClick={() => saveMutation.mutate()}
          className="flex-1 py-2 rounded-lg text-[13px] font-semibold uppercase tracking-[0.12em] bg-brand-accent text-white shadow hover:scale-[1.01] active:scale-[0.99] transition-all disabled:opacity-40"
        >
          {saveMutation.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : t('byok.saveChanges')}
        </Button>
        <button
          type="button"
          onClick={onDone}
          className="h-9 w-9 rounded-lg flex items-center justify-center border border-border text-concrete hover:text-ink hover:bg-muted transition-colors"
        >
          <X size={13} />
        </button>
      </div>
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────
export function ByokSettingsPanel() {
  const { t } = useLanguage()
  const queryClient = useQueryClient()

  const [provider, setProvider] = useState('')
  const [apiKey, setApiKey] = useState('')
  const [alias, setAlias] = useState('')
  const [baseUrl, setBaseUrl] = useState('')
  const [model, setModel] = useState('')
  const [models, setModels] = useState<string[]>([])
  const [loadingModels, setLoadingModels] = useState(false)
  const [keyOk, setKeyOk] = useState(false)
  const [verifying, setVerifying] = useState(false)
  const [editingProvider, setEditingProvider] = useState<string | null>(null)

  const [testing, setTesting] = useState(false)
  const [testResult, setTestResult] = useState<{ ok: boolean; latency?: number; reply?: string; error?: string } | null>(null)

  const { data, isLoading, error } = useQuery({
    queryKey: ['user', 'api-keys'],
    queryFn: loadKeys,
  })

  const invalidate = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: ['user', 'api-keys'] })
    queryClient.invalidateQueries({ queryKey: ['usage', 'current'] })
  }, [queryClient])

  async function onProviderChange(p: string) {
    setProvider(p)
    setApiKey('')
    setBaseUrl(getDefaultBaseUrl(p))
    setKeyOk(false)
    setTestResult(null)
    setModel('')
    setModels([])
  }

  async function refreshModels(p: string, key: string, _baseUrl?: string) {
    if (!p || key.length < 8 || MANUAL_MODEL_PROVIDERS.has(p)) return
    const effectiveBaseUrl = _baseUrl ?? (NEEDS_BASE_URL.has(p) ? baseUrl : undefined)
    setLoadingModels(true)
    try {
      const list = await fetchModelsFromServer(p, key, effectiveBaseUrl)
      if (list.length > 0) { setModels(list); if (!model) setModel(list[0]) }
    } finally { setLoadingModels(false) }
  }

  async function verifyKey() {
    if (!provider || apiKey.length < 8) return
    if (NEEDS_BASE_URL.has(provider) && !baseUrl) { toast.error(t('byok.baseUrlRequired')); return }
    setVerifying(true)
    setTestResult(null)
    try {
      const q = new URLSearchParams({ provider, key: apiKey })
      if (NEEDS_BASE_URL.has(provider) && baseUrl) q.append('baseUrl', baseUrl)
      const res = await fetch(`/api/user/api-keys/verify?${q}`)
      const body = await res.json()
      if (res.ok && body.valid) {
        setKeyOk(true)
        if (Array.isArray(body.models) && body.models.length > 0) { setModels(body.models); if (!model) setModel(body.models[0]) }
        toast.success(t('byok.keyValid'))
      } else {
        setKeyOk(false)
        toast.error(body.message ?? t('byok.keyInvalid'))
      }
    } catch { setKeyOk(false); toast.error(t('byok.verifyError')) }
    finally { setVerifying(false) }
  }

  async function testModel() {
    if (!provider || apiKey.length < 8 || !model) return
    setTesting(true)
    setTestResult(null)
    try {
      const q = new URLSearchParams({ provider, key: apiKey, model })
      if (NEEDS_BASE_URL.has(provider) && baseUrl) q.append('baseUrl', baseUrl)
      const res = await fetch(`/api/user/api-keys/test-model?${q}`)
      setTestResult(await res.json())
    } catch { setTestResult({ ok: false, error: t('byok.contactError') }) }
    finally { setTesting(false) }
  }

  const saveMutation = useMutation({
    mutationFn: async () => {
      const payload: Record<string, string | undefined> = {
        provider, apiKey,
        model: model || undefined,
        alias: alias.trim() || undefined,
      }
      if (NEEDS_BASE_URL.has(provider)) payload.baseUrl = baseUrl
      const res = await fetch('/api/user/api-keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) throw new Error(body.message ?? body.error ?? t('common.error'))
    },
    onSuccess: () => {
      toast.success(t('byok.keySaved', { name: displayName(provider) }))
      setProvider(''); setApiKey(''); setAlias(''); setBaseUrl('')
      setModel(''); setModels([]); setKeyOk(false); setTestResult(null)
      invalidate()
    },
    onError: (err: Error) => toast.error(err.message),
  })

  const toggleMutation = useMutation({
    mutationFn: async ({ p, isActive }: { p: string; isActive: boolean }) => {
      const res = await fetch(`/api/user/api-keys/${encodeURIComponent(p)}`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isActive }),
      })
      if (!res.ok) throw new Error(t('common.error'))
    },
    onSuccess: invalidate,
    onError: () => toast.error(t('byokSettings.error')),
  })

  const deleteMutation = useMutation({
    mutationFn: async (p: string) => {
      const res = await fetch(`/api/user/api-keys/${encodeURIComponent(p)}`, { method: 'DELETE' })
      if (!res.ok) throw new Error(t('common.error'))
    },
    onSuccess: () => { toast.success(t('byok.keyDeleted')); invalidate() },
    onError: () => toast.error(t('byokSettings.error')),
  })

  const allowed = data?.allowedProviders ?? []
  const keys = data?.keys ?? []
  const activeKey = keys.find((k) => k.isActive)
  const tierBlocked = !isLoading && allowed.length === 0
  const saveDisabled = !provider || apiKey.length < 8 || saveMutation.isPending || (NEEDS_BASE_URL.has(provider) && baseUrl.length < 4)
  const canTest = provider && apiKey.length >= 8 && model.length > 0
  const showModelDropdown = !MANUAL_MODEL_PROVIDERS.has(provider) && models.length > 0
  const showModelInput = !!provider && (MANUAL_MODEL_PROVIDERS.has(provider) || (!loadingModels && models.length === 0))

  if (isLoading) return <div className="flex items-center gap-2 text-sm text-muted-foreground p-5"><Loader2 className="h-4 w-4 animate-spin" />{t('byokSettings.loading')}</div>
  if (error) return <p className="text-sm text-destructive p-5">{t('byokSettings.loadError')}</p>

  return (
    <div id="byok" className="bg-white/40 dark:bg-white/5 border border-border rounded-2xl p-8 scroll-mt-6 space-y-6">

      {/* Header */}
      <div className="flex items-start gap-5">
        <div className="p-3 bg-brand-accent/10 rounded-2xl text-brand-accent border border-brand-accent/20"><KeyRound size={18} /></div>
        <div className="flex-1 space-y-1">
          <h3 className="text-[13px] font-bold text-ink">{t('byokSettings.title')}</h3>
          <p className="text-sm text-concrete leading-relaxed">{t('byokSettings.description')}</p>
        </div>
      </div>

      {/* BYOK Status */}
      {!tierBlocked && (
        <div className={cn(
          'flex items-center gap-3 rounded-xl px-4 py-3 text-[11px] font-medium border',
          activeKey
            ? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-500/20'
            : 'bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/20'
        )}>
          {activeKey ? (
            <><Zap size={14} className="shrink-0" /><span>{t('byok.byokActive')} · <strong>{displayName(activeKey.provider)}</strong>{activeKey.model && <> · <code className="font-mono text-[13px]">{activeKey.model}</code></>}{activeKey.alias && <> · {activeKey.alias}</>}</span></>
          ) : (
            <><Shield size={14} className="shrink-0" /><span>{t('byok.noActiveKey')}</span></>
          )}
        </div>
      )}

      {tierBlocked ? (
        <p className="text-[11px] text-amber-600 dark:text-amber-400 bg-amber-500/10 rounded-xl px-4 py-3">{t('byokSettings.tierRequired')}</p>
      ) : (
        <>
          {/* Saved keys */}
          {keys.length > 0 && (
            <div className="space-y-2">
              <p className="text-[13px] font-semibold uppercase tracking-wider text-concrete">{t('byok.savedKeys')}</p>
              <ul className="space-y-1">
                {keys.map((key) => (
                  <li key={key.provider}>
                    <div className={cn(
                      'flex items-center justify-between gap-3 rounded-xl border px-4 py-3 transition-colors',
                      key.isActive ? 'border-emerald-500/30 bg-emerald-500/5' : 'border-border/60',
                      editingProvider === key.provider && 'rounded-b-none border-b-0'
                    )}>
                      <div className="min-w-0 flex items-center gap-3">
                        <div className={cn('h-2 w-2 rounded-full shrink-0', key.isActive ? 'bg-emerald-500' : 'bg-gray-300 dark:bg-white/20')} />
                        <div>
                          <div className="text-[13px] font-semibold text-ink leading-tight">{displayName(key.provider)}</div>
                          <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                            {key.model && <code className="text-[13px] font-mono text-brand-accent bg-brand-accent/10 px-1.5 py-0.5 rounded">{key.model}</code>}
                            {key.alias && <span className="text-[13px] text-concrete">{key.alias}</span>}
                            <span className={cn('text-[13px] font-medium', key.isActive ? 'text-emerald-600 dark:text-emerald-400' : 'text-concrete')}>
                              {key.isActive ? t('byok.activeStatus') : t('byok.inactiveStatus')}
                            </span>
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-1.5 shrink-0">
                        {/* Edit button */}
                        <button
                          type="button"
                          className={cn(
                            'h-7 w-7 rounded-lg flex items-center justify-center transition-colors',
                            editingProvider === key.provider
                              ? 'text-brand-accent bg-brand-accent/10 border border-brand-accent/30'
                              : 'text-concrete hover:text-ink hover:bg-muted border border-transparent'
                          )}
                          onClick={() => setEditingProvider(editingProvider === key.provider ? null : key.provider)}
                        >
                          <Pencil size={12} />
                        </button>
                        {/* Toggle */}
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox" className="sr-only peer" checked={key.isActive}
                            onChange={(e) => toggleMutation.mutate({ p: key.provider, isActive: e.target.checked })}
                            disabled={toggleMutation.isPending}
                          />
                          <div className="w-9 h-5 bg-gray-200 dark:bg-white/10 rounded-full peer peer-checked:after:translate-x-[16px] peer-checked:after:border-white after:content-[''] after:absolute after:top-[3px] after:left-[3px] after:bg-white after:rounded-full after:h-3.5 after:w-3.5 after:transition-all peer-checked:bg-emerald-500" />
                        </label>
                        {/* Delete */}
                        <button
                          type="button"
                          className="h-7 w-7 rounded-lg flex items-center justify-center text-destructive/50 hover:text-destructive hover:bg-rose-50 dark:hover:bg-rose-500/10 transition-colors"
                          disabled={deleteMutation.isPending}
                          onClick={() => { if (confirm(t('byok.confirmDelete', { name: displayName(key.provider) }))) deleteMutation.mutate(key.provider) }}
                        >
                          <Trash2 size={12} />
                        </button>
                      </div>
                    </div>

                    {/* Inline edit form */}
                    {editingProvider === key.provider && (
                      <div className="border border-brand-accent/20 border-t-0 rounded-b-xl overflow-hidden">
                        <EditKeyForm
                          savedKey={key}
                          onDone={() => setEditingProvider(null)}
                          onInvalidate={invalidate}
                        />
                      </div>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Add key form */}
          <div className="space-y-4 border border-border/60 rounded-2xl p-5">
            <p className="text-[13px] font-semibold uppercase tracking-wider text-concrete">
              {keys.length > 0 ? t('byok.addOrReplace') : t('byok.connectProvider')}
            </p>

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-1.5">
                <Label htmlFor="byok-provider" className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byokSettings.provider')}</Label>
                <Select value={provider} onValueChange={onProviderChange} disabled={saveMutation.isPending}>
                  <SelectTrigger id="byok-provider"><SelectValue placeholder={t('byok.chooseProvider')} /></SelectTrigger>
                  <SelectContent>
                    {allowed.map((p) => (
                      <SelectItem key={p} value={p}>
                        <span className="font-medium">{displayName(p)}</span>
                        {providerHint(p) && <span className="ml-2 text-[13px] text-concrete">{providerHint(p)}</span>}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="byok-alias" className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.aliasLabel')} <span className="normal-case font-normal">{t('byok.optional')}</span></Label>
                <Input id="byok-alias" value={alias} onChange={(e) => setAlias(e.target.value)} placeholder={t('byok.aliasPlaceholder')} disabled={saveMutation.isPending} />
              </div>
            </div>

            {NEEDS_BASE_URL.has(provider) && (
              <div className="space-y-1.5">
                <Label htmlFor="byok-baseurl" className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.apiUrl')}</Label>
                <Input id="byok-baseurl" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value.trim())} placeholder="https://api.example.com/v1" disabled={saveMutation.isPending} />
              </div>
            )}

            <div className="space-y-1.5">
              <Label htmlFor="byok-key" className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.apiKey')}</Label>
              <div className="flex gap-2">
                <div className="relative flex-1">
                  <Input
                    id="byok-key" type="password" autoComplete="off" value={apiKey}
                    onChange={(e) => { const val = e.target.value; setApiKey(val); setKeyOk(false); setTestResult(null); refreshModels(provider, val, baseUrl) }}
                    placeholder="sk-..." disabled={saveMutation.isPending}
                    className={cn(keyOk && 'border-emerald-500/60')}
                  />
                  {keyOk && <CheckCircle2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-emerald-500 pointer-events-none" />}
                </div>
                <button
                  type="button" disabled={!provider || apiKey.length < 8 || verifying} onClick={verifyKey}
                  className={cn('shrink-0 px-4 py-2 rounded-xl text-[13px] font-semibold uppercase tracking-[0.1em] transition-all border disabled:opacity-40 disabled:pointer-events-none',
                    keyOk ? 'bg-emerald-500/10 border-emerald-500/40 text-emerald-700 dark:text-emerald-400' : 'bg-white dark:bg-white/5 border-border hover:border-brand-accent/50')}
                >
                  {verifying ? <Loader2 className="h-4 w-4 animate-spin" /> : keyOk ? <CheckCircle2 className="h-4 w-4" /> : t('byok.verify')}
                </button>
              </div>
            </div>

            {provider && (
              <div className="space-y-1.5">
                <Label htmlFor="byok-model" className="text-[13px] font-medium uppercase tracking-wider text-concrete">{t('byok.model')}</Label>
                {loadingModels ? (
                  <div className="flex items-center gap-2 text-xs text-concrete py-2"><Loader2 className="h-3 w-3 animate-spin" />{t('byok.fetchingModels')}</div>
                ) : showModelDropdown ? (
                  <Select value={model} onValueChange={(v) => { setModel(v); setTestResult(null) }} disabled={saveMutation.isPending}>
                    <SelectTrigger id="byok-model"><SelectValue placeholder={t('byok.chooseModel')} /></SelectTrigger>
                    <SelectContent>{models.map((m) => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
                  </Select>
                ) : showModelInput ? (
                  <Input id="byok-model" value={model} onChange={(e) => { setModel(e.target.value); setTestResult(null) }} placeholder="ex. gpt-4o-mini, MiniMax-M2.7" disabled={saveMutation.isPending} />
                ) : null}
              </div>
            )}

            {testResult && (
              <div className={cn('flex items-start gap-3 rounded-xl px-4 py-3 text-[11px] border',
                testResult.ok ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-700 dark:text-emerald-400' : 'bg-rose-500/10 border-rose-500/20 text-rose-700 dark:text-rose-400')}>
                {testResult.ok ? <CheckCircle2 size={14} className="shrink-0 mt-0.5" /> : <XCircle size={14} className="shrink-0 mt-0.5" />}
                <div className="space-y-0.5">
                  {testResult.ok ? (
                    <><p className="font-semibold">{t('byok.modelOperational')}{testResult.latency && <span className="font-normal ml-1">({testResult.latency}ms)</span>}</p>{testResult.reply && <p className="opacity-70 font-mono text-[10px]">{t('byok.reply')} {testResult.reply}</p>}</>
                  ) : <p className="font-semibold">{testResult.error ?? t('byok.testFailed')}</p>}
                </div>
              </div>
            )}

            <div className="flex gap-2">
              <button
                type="button" disabled={!canTest || testing || saveMutation.isPending} onClick={testModel}
                className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-[13px] font-semibold uppercase tracking-[0.1em] transition-all border bg-white dark:bg-white/5 border-border hover:border-brand-accent/50 disabled:opacity-40 disabled:pointer-events-none"
              >
                {testing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FlaskConical size={13} />}{t('byok.test')}
              </button>
              <Button
                type="button" disabled={saveDisabled} onClick={() => saveMutation.mutate()}
                className="flex-1 py-2.5 rounded-xl text-[13px] font-semibold uppercase tracking-[0.15em] transition-all duration-200 bg-brand-accent text-white shadow-lg hover:scale-[1.01] active:scale-[0.99] disabled:opacity-40 disabled:pointer-events-none disabled:shadow-none"
              >
                <div className="flex items-center justify-center gap-2">
                  {saveMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                  {provider ? t('byok.saveWithName', { name: displayName(provider) }) : t('byok.save')}
                </div>
              </Button>
            </div>
          </div>

          {keys.length === 0 && <p className="text-[11px] text-concrete">{t('byokSettings.empty')}</p>}
        </>
      )}
    </div>
  )
}
