import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CrudPage } from '../components/Crud'
import { Badge, Select } from '../components/ui'
import { getSignBoards, bindSignBoard, updateSignBoard, unbindSignBoard, getStores } from '../api/client'

// 간판 패널(ESB 태그) 관제 — 바인딩 상태·디바이스 상태·장애 모니터링.
const BIND = ['ACTIVE', 'UNBOUND', 'ERROR']
const bindTone = (s: string) => s === 'ACTIVE' ? 'green' : s === 'ERROR' ? 'red' : 'gray'
const devTone = (s: string) => s === 'ONLINE' ? 'green' : s === 'OFFLINE' ? 'gray' : 'orange'

export default function SignBoardList() {
  const qc = useQueryClient()
  const [bindStatus, setBindStatus] = 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})` }))
  const unbindMut = useMutation({
    mutationFn: unbindSignBoard,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['signboards'] }),
  })

  return (
    <CrudPage
      title="간판 패널 (ESB)"
      subtitle="e-SignBoard 태그 패널의 바인딩·디바이스 상태 및 장애 모니터링"
      addLabel="패널 바인딩"
      queryKey={['signboards', bindStatus]}
      fetcher={() => getSignBoards(bindStatus ? { bindStatus } : {})}
      onCreate={bindSignBoard} onUpdate={updateSignBoard}
      defaults={{ tenantCode: 'ZIOINFO', bindStatus: 'ACTIVE' }}
      toolbarExtra={
        <>
          <span className="text-xs text-gray-400">바인딩 필터</span>
          <Select value={bindStatus} onChange={setBindStatus}>
            <option value="">전체</option>
            {BIND.map(s => <option key={s} value={s}>{s}</option>)}
          </Select>
        </>
      }
      rowActions={(r: any) => r.bindStatus === 'ACTIVE' ? (
        <button onClick={() => { if (confirm('바인딩 해제?')) unbindMut.mutate(r.id) }}
          className="text-orange-400 hover:text-orange-300 text-xs px-1">해제</button>
      ) : null}
      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: 'productName', header: '표시 상품', render: r => <span className="text-gray-300">{r.productName || '-'}</span> },
        { key: 'locationCode', header: '위치', render: r => <span className="font-mono text-xs text-gray-400">{r.locationCode || '-'}</span> },
        { key: 'templateCode', header: '템플릿', render: r => <span className="font-mono text-xs text-gray-400">{r.templateCode || '-'}</span> },
        { key: 'batteryLevel', header: '배터리', render: r => r.batteryLevel != null ? `${r.batteryLevel}%` : '-' },
        { key: 'deviceStatus', header: '디바이스', render: r => <Badge tone={devTone(r.deviceStatus)}>{r.deviceStatus || '-'}</Badge> },
        { key: 'bindStatus', header: '바인딩', render: r => <Badge tone={bindTone(r.bindStatus)}>{r.bindStatus}</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 (ESL device_id)' },
        { key: 'productCode', label: '상품코드' },
        { key: 'productName', label: '상품명' },
        { key: 'locationCode', label: '위치코드', placeholder: '예: A01-03' },
        { key: 'templateCode', label: '템플릿코드' },
      ]}
    />
  )
}
