import { useState } from 'react'
import { useApi } from '../hooks/useApi'
import { guardiaApi, managerApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import { StatusBadge } from '../components/common/StatusBadge'
import { SlidePanel } from '../components/common/SlidePanel'
import { Btn } from '../components/common/Btn'
import type { Server } from '../api/types'

export default function Servers() {
  const { data, loading, refetch } = useApi<{ items: Server[]; total: number }>(guardiaApi, '/api/cmdb/servers?limit=100')
  const [sel, setSel] = useState<Server | null>(null)
  const [restarting, setRestarting] = useState<string | null>(null)
  const [search, setSearch] = useState('')

  const servers = (data?.items ?? []).filter(s =>
    !search || s.hostname.includes(search) || s.os_type?.toLowerCase().includes(search.toLowerCase())
  )

  const restart = async (svc: string) => {
    setRestarting(svc)
    try { await managerApi.post(`/api/system/services/${svc}/restart`); await refetch() }
    catch (e: unknown) { alert((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '재시작 실패') }
    finally { setRestarting(null) }
  }

  return (
    <>
      <DataTable<Server>
        cols={[
          { key: 'id',        header: 'ID',    width: 60 },
          { key: 'hostname',  header: '호스트명' },
          { key: 'os_type',   header: 'OS 유형' },
          { key: 'inst_name', header: '소속 기관' },
          { key: 'status', header: '상태', render: r => <StatusBadge status={r.status ?? 'unknown'} /> },
        ]}
        rows={servers}
        loading={loading}
        empty="등록된 서버가 없습니다."
        onRowClick={setSel}
        toolbar={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flex: 1 }}>
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
                color: '#94a3b8', fontSize: 13 }}>🔍</span>
              <input value={search} onChange={e => setSearch(e.target.value)}
                placeholder="호스트명 / OS 검색"
                style={{ padding: '7px 12px 7px 30px', border: '1px solid #e2e8f0',
                  borderRadius: 7, fontSize: 13, width: 220, outline: 'none' }} />
            </div>
            <span style={{ fontSize: 12, color: '#64748b' }}>총 {servers.length}대</span>
            <Btn onClick={refetch} size="sm" style={{ marginLeft: 'auto' }}>↺ 새로고침</Btn>
          </div>
        }
      />

      <SlidePanel open={!!sel} onClose={() => setSel(null)} title="서버 상세 정보"
        footer={
          <>
            <Btn onClick={() => setSel(null)} size="sm">닫기</Btn>
            {sel && <Btn variant="primary" size="sm"
              loading={restarting === sel.hostname}
              onClick={() => restart(sel.hostname)}>
              🔄 서비스 재시작
            </Btn>}
          </>
        }>
        {sel && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <StatusBadge status={sel.status ?? 'unknown'} />
            {[
              ['호스트명', sel.hostname],
              ['OS 유형', sel.os_type],
              ['기관', sel.inst_name ?? '-'],
              ['서버 ID', String(sel.id)],
            ].map(([k, v]) => (
              <div key={k}>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b',
                  textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 4 }}>{k}</div>
                <div style={{ fontSize: 14 }}>{v}</div>
              </div>
            ))}
          </div>
        )}
      </SlidePanel>
    </>
  )
}
