import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getSettings, updateSetting } from '../api/client'

const categoryColor: Record<string, string> = {
  GENERAL: 'bg-gray-500/20 text-gray-300',
  ESL:     'bg-purple-500/20 text-purple-300',
  ALARM:   'bg-amber-500/20 text-amber-300',
  AI:      'bg-cyan-500/20 text-cyan-300',
}

export default function SystemSettings() {
  const qc = useQueryClient()
  const [editing, setEditing] = useState<Record<string, string>>({})

  const { data: settings = [], isLoading } = useQuery({
    queryKey: ['settings'],
    queryFn:  () => getSettings(),
  })

  const save = useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) => updateSetting(key, value),
    onSuccess: (_d, vars) => {
      qc.invalidateQueries({ queryKey: ['settings'] })
      setEditing(e => { const n = { ...e }; delete n[vars.key]; return n })
    },
  })

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-white">시스템 설정</h1>
      <p className="text-xs text-gray-500">
        운영 설정 변경은 감사 로그에 기록됩니다. (변경은 ADMIN 권한 필요)
      </p>

      <div className="bg-card border border-edge rounded-lg overflow-hidden">
        <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[]).map((s: any) => {
              const isEdit = s.settingKey in editing
              return (
                <tr key={s.settingKey} className="border-b border-edge hover:bg-edge/30">
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs ${categoryColor[s.category] || 'bg-gray-500/20 text-gray-400'}`}>
                      {s.category}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-200 font-mono text-xs">{s.settingKey}</td>
                  <td className="px-4 py-3">
                    {isEdit ? (
                      <input
                        value={editing[s.settingKey]}
                        onChange={e => setEditing(ed => ({ ...ed, [s.settingKey]: e.target.value }))}
                        className="bg-panel border border-brand/60 rounded px-2 py-1 text-sm text-gray-100 w-48" />
                    ) : (
                      <span className="text-gray-300">{s.settingValue}</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-gray-500 text-xs max-w-xs">{s.description || '-'}</td>
                  <td className="px-4 py-3 text-gray-500 text-xs">
                    {s.updatedAt ? new Date(s.updatedAt).toLocaleString('ko-KR') : '-'}
                  </td>
                  <td className="px-4 py-3 text-right">
                    {isEdit ? (
                      <div className="flex gap-2 justify-end">
                        <button
                          onClick={() => save.mutate({ key: s.settingKey, value: editing[s.settingKey] })}
                          disabled={save.isPending}
                          className="text-xs px-3 py-1 rounded bg-brand/80 text-white hover:bg-brand">저장</button>
                        <button
                          onClick={() => setEditing(e => { const n = { ...e }; delete n[s.settingKey]; return n })}
                          className="text-xs px-3 py-1 rounded bg-edge/60 text-gray-300 hover:bg-edge">취소</button>
                      </div>
                    ) : (
                      <button
                        onClick={() => setEditing(e => ({ ...e, [s.settingKey]: s.settingValue ?? '' }))}
                        className="text-xs px-3 py-1 rounded bg-edge/60 text-gray-300 hover:bg-edge">수정</button>
                    )}
                  </td>
                </tr>
              )
            })}
            {(settings as any[]).length === 0 && (
              <tr><td colSpan={6} className="px-4 py-8 text-center text-gray-500">설정이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
