import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Settings as SettingsIcon, Plug, ShieldCheck } from 'lucide-react'
import { getProviders, getSettings, updateSetting } from '../api/client'

export default function Settings() {
  const qc = useQueryClient()
  const { data: providers } = useQuery({ queryKey: ['providers'], queryFn: getProviders })
  const { data: settings } = useQuery({ queryKey: ['settings'], queryFn: getSettings })
  const [edits, setEdits] = useState<Record<string, string>>({})

  const save = async (key: string) => { const v = edits[key]; if (v === undefined) return; await updateSetting(key, v).catch(() => {}); qc.invalidateQueries({ queryKey: ['settings'] }) }

  // providers: 활성 provider 상태(키 미노출). 객체/배열 양쪽 대응.
  const provList = Array.isArray(providers)
    ? providers
    : Object.entries(providers || {}).map(([k, v]: any) => ({ adapter: k, provider: typeof v === 'string' ? v : v?.provider, active: v?.active ?? true }))

  return (
    <div>
      <div className="flex items-center gap-2 mb-5"><SettingsIcon className="text-brand" size={22} /><h1 className="text-xl font-bold">Gateways · Settings</h1></div>

      <div className="bg-card border border-edge rounded-xl p-5 mb-5">
        <div className="flex items-center gap-2 text-sm font-semibold mb-3"><Plug size={16} className="text-brand" /> Gateway Adapters (provider)</div>
        <p className="text-xs text-slate-500 mb-3 flex items-center gap-1.5"><ShieldCheck size={13} className="text-accent" /> API keys are stored only in environment variables and are never shown on screen. (Default mock = 0 external calls)</p>
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-3">
          {provList.map((p: any, i: number) => (
            <div key={i} className="bg-panel border border-edge rounded-lg p-3 flex items-center justify-between">
              <div>
                <div className="text-xs text-slate-400 uppercase">{p.adapter}</div>
                <div className="font-semibold">{p.provider || 'mock'}</div>
              </div>
              <span className={`text-xs px-2 py-1 rounded ${p.provider && p.provider !== 'mock' ? 'bg-emerald-500/15 text-emerald-400' : 'bg-slate-600/20 text-slate-400'}`}>{p.provider && p.provider !== 'mock' ? 'Live' : 'mock'}</span>
            </div>
          ))}
          {!provList.length && <div className="text-slate-500 text-sm">Unable to load provider information.</div>}
        </div>
      </div>

      <div className="bg-card border border-edge rounded-xl p-5">
        <div className="text-sm font-semibold mb-3">System Settings</div>
        <div className="space-y-2">
          {(settings || []).map((s: any) => {
            const key = s.key || s.settingKey
            const cur = edits[key] ?? s.value ?? s.settingValue ?? ''
            return (
              <div key={key} className="flex items-center gap-3">
                <span className="text-sm text-slate-400 w-56 font-mono text-xs">{key}</span>
                <input value={cur} onChange={e => setEdits({ ...edits, [key]: e.target.value })} className="flex-1 bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
                <button onClick={() => save(key)} className="bg-brand2 text-white text-xs px-3 py-2 rounded-lg">Save</button>
              </div>
            )
          })}
          {!(settings || []).length && <div className="text-slate-500 text-sm py-4">No settings available.</div>}
        </div>
      </div>
    </div>
  )
}
