import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Trash2, Star } from 'lucide-react'
import { getFirmware, deleteFirmware } from '../api/client'

export default function FirmwareList() {
  const qc = useQueryClient()
  const { data: fws = [], isLoading } = useQuery({
    queryKey: ['firmware'],
    queryFn:  () => getFirmware(),
  })

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

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

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-white">펌웨어 관리</h1>
      <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>
            {(fws as any[]).map((f: any) => (
              <tr key={f.id} className="border-b border-edge hover:bg-edge/30">
                <td className="px-4 py-3 text-brand font-mono text-xs">{f.firmwareVersion}</td>
                <td className="px-4 py-3 text-gray-400 text-xs">{f.tenantCode}</td>
                <td className="px-4 py-3 text-gray-300 text-xs">{f.deviceType}</td>
                <td className="px-4 py-3 text-gray-300 text-xs">{f.fileName}</td>
                <td className="px-4 py-3 text-gray-400 text-xs">
                  {f.fileSize ? `${(f.fileSize / 1024).toFixed(1)}KB` : '-'}
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs font-mono truncate max-w-[80px]">
                  {f.checksum ? f.checksum.substring(0, 8) + '...' : '-'}
                </td>
                <td className="px-4 py-3">
                  {f.latest && <Star size={14} className="text-yellow-400" fill="currentColor" />}
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {f.createdAt ? new Date(f.createdAt).toLocaleDateString('ko-KR') : '-'}
                </td>
                <td className="px-4 py-3">
                  <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(f.id) }}
                    className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
                </td>
              </tr>
            ))}
            {(fws as any[]).length === 0 && (
              <tr><td colSpan={9} className="px-4 py-8 text-center text-gray-500">펌웨어가 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
