import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Cpu, Wifi, WifiOff, Battery, AlertTriangle } from 'lucide-react'
import { getHCore, updateHCoreStatus } from '../api/client'

const statusIcon: Record<string, React.ReactNode> = {
  ONLINE:   <Wifi size={14} className="text-green-400" />,
  OFFLINE:  <WifiOff size={14} className="text-red-400" />,
  ERROR:    <AlertTriangle size={14} className="text-orange-400" />,
  UPDATING: <Cpu size={14} className="text-yellow-400" />,
}

const statusColor: Record<string, string> = {
  ONLINE:   'border-green-500/30 bg-green-500/5',
  OFFLINE:  'border-red-500/30 bg-red-500/5',
  ERROR:    'border-orange-500/30 bg-orange-500/5',
  UPDATING: 'border-yellow-500/30 bg-yellow-500/5',
}

export default function HCoreStatus() {
  const qc = useQueryClient()
  const [deviceType, setDeviceType] = React.useState('')
  const [status, setStatus] = React.useState('')

  const { data: devices = [], isLoading } = useQuery({
    queryKey: ['hcore', deviceType, status],
    queryFn:  () => getHCore({ deviceType: deviceType || undefined, status: status || undefined }),
    refetchInterval: 15000,
  })

  const statusMut = useMutation({
    mutationFn: ({ id, status }: { id: number; status: string }) => updateHCoreStatus(id, status),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['hcore'] }),
  })

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-white">HCore 장치 현황</h1>
        <div className="flex gap-2">
          <select value={deviceType} onChange={e => setDeviceType(e.target.value)}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300">
            <option value="">전체 유형</option>
            {['GATEWAY','HUB','ESL_DEVICE'].map(t => <option key={t} value={t}>{t}</option>)}
          </select>
          <select value={status} onChange={e => setStatus(e.target.value)}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300">
            <option value="">전체 상태</option>
            {['ONLINE','OFFLINE','ERROR','UPDATING'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
        {(devices as any[]).map((d: any) => (
          <div key={d.id} className={`border rounded-lg p-4 ${statusColor[d.status] || 'border-edge bg-card'}`}>
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                {statusIcon[d.status]}
                <span className="text-xs font-mono text-gray-300">{d.deviceId}</span>
              </div>
              <span className="text-xs text-brand">{d.deviceType}</span>
            </div>
            <p className="text-xs text-gray-400">{d.storeName || '미배정'}</p>
            <p className="text-xs text-gray-500 mt-1">FW: {d.firmwareVersion || '-'}</p>
            {d.ipAddress && <p className="text-xs text-gray-600 font-mono">{d.ipAddress}</p>}
            {d.batteryLevel != null && (
              <div className="flex items-center gap-1 mt-2">
                <Battery size={12} className={d.batteryLevel < 20 ? 'text-red-400' : 'text-gray-400'} />
                <span className={`text-xs ${d.batteryLevel < 20 ? 'text-red-400' : 'text-gray-400'}`}>
                  {d.batteryLevel}%
                </span>
              </div>
            )}
            {d.status === 'OFFLINE' && (
              <button
                onClick={() => statusMut.mutate({ id: d.id, status: 'ONLINE' })}
                className="mt-2 text-xs text-brand hover:underline"
              >
                온라인으로 변경
              </button>
            )}
          </div>
        ))}
        {(devices as any[]).length === 0 && (
          <div className="col-span-4 text-center text-gray-500 py-8">장치가 없습니다</div>
        )}
      </div>
    </div>
  )
}

import React from 'react'
