import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CheckCircle, Trash2 } from 'lucide-react'
import AlarmBadge from '../components/AlarmBadge'
import { getAlarms, resolveAlarm, deleteAlarm } from '../api/client'

export default function AlarmList() {
  const qc = useQueryClient()
  const [severity, setSeverity] = useState('')
  const [status,   setStatus]   = useState('OPEN')

  const { data: alarms = [], isLoading } = useQuery({
    queryKey: ['alarms', severity, status],
    queryFn:  () => getAlarms({ severity: severity || undefined, status: status || undefined }),
  })

  const resolveMut = useMutation({
    mutationFn: ({ id, resolution }: { id: number, resolution: string }) =>
      resolveAlarm(id, resolution),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['alarms'] }),
  })

  const deleteMut = useMutation({
    mutationFn: deleteAlarm,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['alarms'] }),
  })

  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">알람 관리</h1>
        <div className="flex gap-2">
          <select value={severity} onChange={e => setSeverity(e.target.value)}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300">
            <option value="">전체 심각도</option>
            {['CRITICAL','HIGH','MEDIUM','LOW'].map(s =>
              <option key={s} value={s}>{s}</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>
            {['OPEN','ACKNOWLEDGED','RESOLVED'].map(s =>
              <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      <div className="bg-card border border-edge rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-panel border-b border-edge">
            <tr>
              {['매장','유형','심각도','메시지','상태','발생일시','액션'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(alarms as any[]).map((a: any) => (
              <tr key={a.id} className="border-b border-edge hover:bg-edge/30 transition-colors">
                <td className="px-4 py-3 text-gray-300">{a.storeName || '-'}</td>
                <td className="px-4 py-3 text-gray-300">{a.alarmType}</td>
                <td className="px-4 py-3"><AlarmBadge severity={a.severity} /></td>
                <td className="px-4 py-3 text-gray-400 max-w-xs truncate">{a.message}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${
                    a.status === 'RESOLVED' ? 'bg-green-500/20 text-green-400' :
                    a.status === 'OPEN'     ? 'bg-red-500/20 text-red-400' :
                    'bg-yellow-500/20 text-yellow-400'
                  }`}>{a.status}</span>
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {a.createdAt ? new Date(a.createdAt).toLocaleString('ko-KR') : '-'}
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    {a.status !== 'RESOLVED' && (
                      <button
                        onClick={() => resolveMut.mutate({ id: a.id, resolution: '운영자 확인 후 해결' })}
                        className="text-green-400 hover:text-green-300"
                        title="해결 처리"
                      >
                        <CheckCircle size={14} />
                      </button>
                    )}
                    <button
                      onClick={() => { if (confirm('삭제?')) deleteMut.mutate(a.id) }}
                      className="text-red-400 hover:text-red-300"
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {(alarms as any[]).length === 0 && (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-500">알람이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
