import { useApi } from '../hooks/useApi'
import { guardiaApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import { StatusBadge } from '../components/common/StatusBadge'
import type { User } from '../api/types'

const ROLE_LABEL: Record<string, string> = { admin:'관리자', pm:'PM', engineer:'엔지니어', customer:'고객' }

export default function Users() {
  const { data, loading } = useApi<User[]>(guardiaApi, '/api/auth/users')
  const users = data ?? []

  return (
    <DataTable<User>
      cols={[
        { key: 'id',           header: 'ID',     width: 60 },
        { key: 'username',     header: '아이디' },
        { key: 'display_name', header: '이름' },
        { key: 'email',        header: '이메일' },
        { key: 'role',         header: '역할', render: r => (
          <span style={{ fontSize: 11, background: r.role === 'admin' ? '#e8ecff' : '#f1f5f9',
            color: r.role === 'admin' ? '#4f6ef7' : '#64748b',
            padding: '2px 8px', borderRadius: 10 }}>
            {ROLE_LABEL[r.role] ?? r.role}
          </span>
        )},
        { key: 'is_active', header: '상태', render: r =>
          <StatusBadge status={r.is_active ? 'active' : 'inactive'} /> },
      ]}
      rows={users}
      loading={loading}
      empty="사용자 목록을 불러올 수 없습니다. (admin 권한 필요)"
      toolbar={
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <span style={{ fontSize: 12, color: '#64748b' }}>총 {users.length}명</span>
          <a href="http://zioinfo.co.kr:8001/api/auth/users" target="_blank" rel="noreferrer"
            style={{ fontSize: 11, color: '#4f6ef7', marginLeft: 'auto' }}>
            ITSM에서 관리 →
          </a>
        </div>
      }
    />
  )
}
