import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Toolbar, Select, Badge } from '../components/ui'
import { getSettings, updateSetting } from '../api/client'

// 시스템 설정 — 카테고리별 key/value 설정. 인라인 편집. 자격증명성 값은 백엔드에서 마스킹.
const CATS = ['', 'GENERAL', 'ESL', 'ALARM', 'AI']

export default function SystemSettings() {
  const qc = useQueryClient()
  const [category, setCategory] = useState('')
  const { data: settings = [], isLoading } = useQuery({
    queryKey: ['settings', category],
    queryFn: () => getSettings(category || undefined),
  })
  const saveMut = useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) => updateSetting(key, value),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['settings'] }),
  })

  return (
    <div>
      <PageHeader title="시스템 설정" subtitle="카테고리별 운영 파라미터 관리" />
      <Toolbar>
        <span className="text-xs text-gray-400">카테고리</span>
        <Select value={category} onChange={setCategory}>
          {CATS.map(c => <option key={c} value={c}>{c || '전체'}</option>)}
        </Select>
      </Toolbar>

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <div className="bg-card border border-edge rounded-lg overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-panel border-b border-edge">
              <tr>{['카테고리', '키', '값', '설명', ''].map(h => <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>)}</tr>
            </thead>
            <tbody>
              {(settings as any[]).length === 0 ? (
                <tr><td colSpan={5} className="px-4 py-10 text-center text-gray-500">설정이 없습니다.</td></tr>
              ) : (settings as any[]).map(s => <SettingRow key={s.settingKey} s={s} onSave={(v) => saveMut.mutate({ key: s.settingKey, value: v })} />)}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

function SettingRow({ s, onSave }: { s: any; onSave: (v: string) => void }) {
  const [val, setVal] = useState(s.settingValue ?? '')
  const dirty = val !== (s.settingValue ?? '')
  return (
    <tr className="border-b border-edge/70">
      <td className="px-4 py-2.5"><Badge tone="blue">{s.category}</Badge></td>
      <td className="px-4 py-2.5 font-mono text-xs text-white">{s.settingKey}</td>
      <td className="px-4 py-2.5">
        <input value={val} onChange={e => setVal(e.target.value)}
          className="bg-ink border border-edge rounded px-2 py-1 text-xs text-gray-200 outline-none focus:border-brand w-56" />
      </td>
      <td className="px-4 py-2.5 text-xs text-gray-400">{s.description}</td>
      <td className="px-4 py-2.5">
        <button onClick={() => onSave(val)} disabled={!dirty}
          className="text-xs px-2 py-1 rounded bg-brand text-white disabled:opacity-30">저장</button>
      </td>
    </tr>
  )
}
