import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { CrudPage } from '../components/Crud'
import { Badge, Select } from '../components/ui'
import { getGateways, createGateway, updateGateway, deleteGateway, getStores } from '../api/client'

// 게이트웨이 관제 — GEN1/GEN2/GEN2_PLUS_EMS 세대별 상태·장애 모니터링.
const GW_TYPES = ['GEN1', 'GEN2', 'GEN2_PLUS_EMS']
const DEV_TYPES = ['GATEWAY', 'HUB', 'ESB_TAG']
const STATUSES = ['ONLINE', 'OFFLINE', 'ERROR', 'UPDATING']
const statusTone = (s: string) => s === 'ONLINE' ? 'green' : s === 'ERROR' ? 'red' : s === 'UPDATING' ? 'yellow' : 'gray'

export default function GatewayList() {
  const [status, setStatus] = useState('')
  const { data: stores = [] } = useQuery({ queryKey: ['stores'], queryFn: () => getStores() })
  const storeOpts = (stores as any[]).map(s => ({ value: String(s.id), label: `${s.storeName} (${s.storeCode})` }))

  return (
    <CrudPage
      title="게이트웨이 관제"
      subtitle="Gateway/Hub 세대(GEN1·GEN2·GEN2+EMS) 상태 및 장애 모니터링"
      addLabel="게이트웨이 등록"
      queryKey={['gateways', status]}
      fetcher={() => getGateways(status ? { status } : {})}
      onCreate={createGateway} onUpdate={updateGateway} onDelete={deleteGateway}
      defaults={{ tenantCode: 'ZIOINFO', deviceType: 'GATEWAY', gwType: 'GEN2', status: 'ONLINE' }}
      toolbarExtra={
        <>
          <span className="text-xs text-gray-400">상태 필터</span>
          <Select value={status} onChange={setStatus}>
            <option value="">전체</option>
            {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
          </Select>
        </>
      }
      columns={[
        { key: 'deviceId', header: '장치 ID', render: r => <span className="font-mono text-xs text-white">{r.deviceId}</span> },
        { key: 'storeName', header: '매장', render: r => <span className="text-gray-300">{r.storeName || '-'}</span> },
        { key: 'deviceType', header: '유형', render: r => <span className="text-xs text-gray-400">{r.deviceType}</span> },
        { key: 'gwType', header: '세대', render: r => <Badge tone="blue">{r.gwType}</Badge> },
        { key: 'firmwareVersion', header: '펌웨어', render: r => <span className="font-mono text-xs text-gray-400">{r.firmwareVersion || '-'}</span> },
        { key: 'batteryLevel', header: '배터리', render: r => r.batteryLevel != null ? <span className="text-xs">{r.batteryLevel}%</span> : '-' },
        { key: 'status', header: '상태', render: r => <Badge tone={statusTone(r.status)}>{r.status}</Badge> },
      ]}
      form={[
        { key: 'tenantCode', label: '테넌트', type: 'select', opts: ['ZIOINFO', 'TENANT_A', 'TENANT_B', 'EMART'] },
        { key: 'storeId', label: '매장', type: 'select', opts: storeOpts },
        { key: 'deviceId', label: '장치 ID' },
        { key: 'deviceType', label: '장치 유형', type: 'select', opts: DEV_TYPES },
        { key: 'gwType', label: '게이트웨이 세대', type: 'select', opts: GW_TYPES },
        { key: 'firmwareVersion', label: '펌웨어 버전' },
        { key: 'macAddress', label: 'MAC 주소' },
        { key: 'status', label: '상태', type: 'select', opts: STATUSES },
      ]}
    />
  )
}
