import { useEffect, useState } from 'react'
import { Settings, Save } from 'lucide-react'
import { getSettings, updateSetting } from '../api/client'
import { isSuperAdmin } from '../components/rbac'

interface Setting { key: string; value: string; description?: string }

export default function SystemSettings() {
  const [list, setList] = useState<Setting[]>([])
  const [drafts, setDrafts] = useState<Record<string, string>>({})
  const [msg, setMsg] = useState('')
  const [err, setErr] = useState('')
  const editable = isSuperAdmin()

  const load = () =>
    getSettings()
      .then(r => {
        const data: any = r.data?.data || []
        const arr: Setting[] = Array.isArray(data) ? data : Object.entries(data).map(([key, value]) => ({ key, value: String(value) }))
        setList(arr); setErr('')
      })
      .catch(e => setErr(e?.response?.status === 403 ? '권한이 없습니다 (Manager+).' : '시스템 설정을 불러오지 못했습니다.'))
  useEffect(() => { load() }, [])

  const save = async (key: string) => {
    setMsg(''); setErr('')
    try { await updateSetting(key, drafts[key] ?? ''); setMsg(`'${key}' 저장됨`); load() }
    catch (e: any) { setErr(e?.response?.status === 403 ? 'SuperAdmin 권한이 필요합니다.' : '저장 실패') }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-bold flex items-center gap-2"><Settings className="text-brand" size={20} /> 시스템 설정</h1>
      </div>

      {msg && <div className="bg-brand/10 border border-brand/30 text-brand text-sm rounded-lg px-4 py-2.5 mb-4">{msg}</div>}
      {err && <div className="bg-rose-500/10 border border-rose-500/40 text-rose-300 text-sm rounded-lg px-4 py-2.5 mb-4">{err}</div>}
      {!editable && <div className="bg-amber-500/10 border border-amber-500/30 text-amber-300 text-sm rounded-lg px-4 py-2.5 mb-4">조회 전용입니다. 설정 변경은 SuperAdmin 권한이 필요합니다.</div>}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-slate-500 text-xs bg-panel">
            <tr><th className="text-left py-3 px-4">키</th><th className="text-left">값</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(s => (
              <tr key={s.key} className="border-t border-edge/50">
                <td className="py-3 px-4 font-mono text-xs text-brand align-top">
                  {s.key}
                  {s.description && <div className="text-[11px] text-slate-500 font-sans mt-0.5">{s.description}</div>}
                </td>
                <td className="py-3">
                  <input className="inp" defaultValue={s.value} disabled={!editable}
                    onChange={e => setDrafts({ ...drafts, [s.key]: e.target.value })} />
                </td>
                <td className="px-4 text-right align-top">
                  {editable && (
                    <button onClick={() => save(s.key)} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand text-ink text-xs font-semibold">
                      <Save size={13} /> 저장
                    </button>
                  )}
                </td>
              </tr>
            ))}
            {list.length === 0 && <tr><td colSpan={3} className="py-6 text-center text-slate-500">설정 항목이 없습니다.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
