import { useApi } from '../hooks/useApi'
import { managerApi } from '../api/clients'
import { Btn } from '../components/common/Btn'
import { useState } from 'react'

export default function ConfigEnv() {
  const { data, loading, refetch } = useApi<Record<string, string>>(managerApi, '/api/config/env')
  const [reloading, setReloading] = useState(false)
  const [msg, setMsg] = useState<{ text: string; ok: boolean } | null>(null)

  const nginxReload = async () => {
    setReloading(true)
    try {
      await managerApi.post('/api/config/nginx/reload')
      setMsg({ text: 'Nginx 리로드 완료', ok: true })
    } catch (e: unknown) {
      setMsg({ text: (e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '실패', ok: false })
    } finally { setReloading(false); setTimeout(() => setMsg(null), 4000) }
  }

  const envEntries = Object.entries(data ?? {})

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 800 }}>
      {msg && (
        <div style={{ padding: '10px 16px', borderRadius: 8, fontSize: 13,
          background: msg.ok ? '#dcfce7' : '#fee2e2',
          color: msg.ok ? '#16a34a' : '#dc2626',
          border: `1px solid ${msg.ok ? '#bbf7d0' : '#fecaca'}` }}>
          {msg.ok ? '✅' : '❌'} {msg.text}
        </div>
      )}

      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
        padding: '18px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>환경변수 (.env)</h3>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn size="sm" onClick={refetch}>↺ 새로고침</Btn>
            <Btn variant="primary" size="sm" loading={reloading} onClick={nginxReload}>
              🔄 Nginx 리로드
            </Btn>
          </div>
        </div>

        {loading ? <div style={{ color: '#94a3b8', fontSize: 13 }}>로딩 중...</div> : (
          <div style={{ background: '#f8fafc', borderRadius: 8, border: '1px solid #e2e8f0',
            overflow: 'hidden' }}>
            {envEntries.map(([k, v], i) => (
              <div key={k} style={{
                display: 'grid', gridTemplateColumns: '240px 1fr',
                borderBottom: i < envEntries.length - 1 ? '1px solid #f1f5f9' : 'none',
              }}>
                <div style={{ padding: '10px 14px', fontFamily: 'monospace', fontSize: 12,
                  color: '#1a3a6b', fontWeight: 600, borderRight: '1px solid #f1f5f9',
                  background: '#f0f2f5' }}>{k}</div>
                <div style={{ padding: '10px 14px', fontFamily: 'monospace', fontSize: 12,
                  color: v === '****' ? '#94a3b8' : '#1e293b', fontStyle: v === '****' ? 'italic' : 'normal' }}>
                  {v}
                </div>
              </div>
            ))}
            {envEntries.length === 0 && (
              <div style={{ padding: '24px', color: '#94a3b8', fontSize: 13, textAlign: 'center' }}>
                환경변수를 불러올 수 없습니다. (admin 권한 필요)
              </div>
            )}
          </div>
        )}
        <div style={{ marginTop: 12, fontSize: 11, color: '#94a3b8' }}>
          🔒 SECRET/PASSWORD/KEY 값은 보안상 마스킹됩니다. 직접 편집: SSH 접속 후 <code>/opt/guardia/app/.env</code>
        </div>
      </div>
    </div>
  )
}
