import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Toolbar, Table, Badge, Select, Button } from '../components/ui'
import { Icon } from '../lib/icons'
import { getAlarms, resolveAlarm, deleteAlarm } from '../api/client'

// 알람/장애 관리 — DEVICE/NETWORK/BATTERY/FIRMWARE/SYSTEM 알람 대응.
const SEV = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']
const STATUS = ['OPEN', 'ACKNOWLEDGED', 'RESOLVED']
const sevTone = (s: string) => s === 'CRITICAL' ? 'red' : s === 'HIGH' ? 'orange' : s === 'MEDIUM' ? 'yellow' : 'gray'
const stTone = (s: string) => s === 'RESOLVED' ? 'green' : s === 'ACKNOWLEDGED' ? 'yellow' : 'red'

export default function AlarmList() {
  const qc = useQueryClient()
  const [status, setStatus] = useState('')
  const [severity, setSeverity] = useState('')
  const { data: alarms = [], isLoading } = useQuery({
    queryKey: ['alarms', status, severity],
    queryFn: () => getAlarms({ ...(status && { status }), ...(severity && { severity }) }),
    refetchInterval: 30000,
  })
  const resolveMut = useMutation({
    mutationFn: ({ id, resolution }: { id: number; resolution: string }) => resolveAlarm(id, resolution),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['alarms'] }),
  })
  const delMut = useMutation({ mutationFn: deleteAlarm, onSuccess: () => qc.invalidateQueries({ queryKey: ['alarms'] }) })

  return (
    <div>
      <PageHeader title="알람 / 장애" subtitle="디바이스·네트워크·배터리·펌웨어·시스템 장애 실시간 모니터링(30초 갱신)" />
      <Toolbar>
        <span className="text-xs text-gray-400">상태</span>
        <Select value={status} onChange={setStatus}>
          <option value="">전체</option>{STATUS.map(s => <option key={s} value={s}>{s}</option>)}
        </Select>
        <span className="text-xs text-gray-400 ml-2">심각도</span>
        <Select value={severity} onChange={setSeverity}>
          <option value="">전체</option>{SEV.map(s => <option key={s} value={s}>{s}</option>)}
        </Select>
      </Toolbar>

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <Table
          rowKey={(r: any) => r.id}
          rows={alarms as any[]}
          columns={[
            { key: 'severity', header: '심각도', render: r => <Badge tone={sevTone(r.severity)}>{r.severity}</Badge> },
            { key: 'alarmType', header: '유형', render: r => <span className="text-xs text-gray-400">{r.alarmType}</span> },
            { key: 'storeName', header: '매장', render: r => <span className="text-gray-300">{r.storeName || '-'}</span> },
            { key: 'message', header: '메시지', render: r => <span className="text-gray-300">{r.message}</span> },
            { key: 'status', header: '상태', render: r => <Badge tone={stTone(r.status)}>{r.status}</Badge> },
            { key: '__act', header: '', align: 'right', render: (r: any) => (
              <div className="flex gap-2 justify-end items-center">
                {r.status !== 'RESOLVED' && (
                  <Button variant="ghost" icon="check" onClick={() => {
                    const res = prompt('해결 내용을 입력하세요', '조치 완료')
                    if (res != null) resolveMut.mutate({ id: r.id, resolution: res })
                  }}>해결</Button>
                )}
                <button onClick={() => { if (confirm('삭제?')) delMut.mutate(r.id) }} className="text-red-400 hover:text-red-300"><Icon name="trash" size={15} /></button>
              </div>
            ) },
          ]}
        />
      )}
    </div>
  )
}
