import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CheckCircle, XCircle, Clock, Send, AlertCircle, RefreshCw } from 'lucide-react'
import api from '../api/client'

interface QueueItem {
  id: number; tenantCode: string; storeId: number; storeName: string
  deviceId: string; locationCode: string; productCode: string; productName: string
  newPrice: number; newSalePrice: number; templateCode: string
  priority: number; status: string; retryCount: number; maxRetry: number
  errorMessage: string; sentAt: string; confirmedAt: string; createdAt: string
}

const statusMeta: Record<string, { icon: React.ReactNode; color: string; label: string }> = {
  PENDING:   { icon: <Clock size={13}       />, color: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/30', label: '대기' },
  SENDING:   { icon: <Send size={13}        />, color: 'text-blue-400 bg-blue-500/10 border-blue-500/30',     label: '전송중' },
  SENT:      { icon: <Send size={13}        />, color: 'text-cyan-400 bg-cyan-500/10 border-cyan-500/30',     label: '전송됨' },
  CONFIRMED: { icon: <CheckCircle size={13} />, color: 'text-green-400 bg-green-500/10 border-green-500/30', label: '확인됨' },
  FAILED:    { icon: <XCircle size={13}     />, color: 'text-red-400 bg-red-500/10 border-red-500/30',       label: '실패' },
  CANCELLED: { icon: <AlertCircle size={13} />, color: 'text-gray-400 bg-gray-500/10 border-gray-500/30',   label: '취소됨' },
}

export default function UpdateQueueList() {
  const qc = useQueryClient()
  const [tenantCode, setTenantCode] = useState('')
  const [status, setStatus]         = useState('')

  const { data: items = [], isLoading, refetch } = useQuery<QueueItem[]>({
    queryKey: ['update-queue', tenantCode, status],
    queryFn:  () => api.get('/update-queue', { params: {
      tenantCode: tenantCode || undefined,
      status:     status     || undefined,
    }}).then(r => r.data.data),
    refetchInterval: 5000,
  })

  const cancelMut = useMutation({
    mutationFn: (id: number) => api.put(`/update-queue/${id}/cancel`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['update-queue'] }),
  })

  const pendingCount   = items.filter(i => i.status === 'PENDING').length
  const failedCount    = items.filter(i => i.status === 'FAILED').length
  const confirmedCount = items.filter(i => i.status === 'CONFIRMED').length

  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">e-paper 가격 업데이트 큐</h1>
        <button onClick={() => refetch()} className="flex items-center gap-1.5 px-3 py-1.5 bg-edge text-gray-300 rounded text-sm">
          <RefreshCw size={13} /> 새로고침
        </button>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: '대기중', count: pendingCount,   color: 'text-yellow-400', bg: 'bg-yellow-500/5 border-yellow-500/20' },
          { label: '실패',   count: failedCount,    color: 'text-red-400',    bg: 'bg-red-500/5 border-red-500/20' },
          { label: '완료',   count: confirmedCount, color: 'text-green-400',  bg: 'bg-green-500/5 border-green-500/20' },
        ].map(({ label, count, color, bg }) => (
          <div key={label} className={`border rounded-lg p-3 ${bg}`}>
            <div className={`text-2xl font-bold font-mono ${color}`}>{count}</div>
            <div className="text-xs text-gray-400 mt-0.5">{label}</div>
          </div>
        ))}
      </div>

      {/* 필터 */}
      <div className="flex gap-3">
        <input value={tenantCode} onChange={e => setTenantCode(e.target.value)}
          placeholder="테넌트 필터"
          className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300 w-40"
        />
        <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>
          {Object.entries(statusMeta).map(([k, v]) => (
            <option key={k} value={k}>{v.label}</option>
          ))}
        </select>
      </div>

      {/* 큐 목록 */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-edge text-xs text-gray-500">
              <th className="text-left py-2 px-3">#</th>
              <th className="text-left py-2 px-3">태그 ID</th>
              <th className="text-left py-2 px-3">위치</th>
              <th className="text-left py-2 px-3">상품</th>
              <th className="text-right py-2 px-3">가격</th>
              <th className="text-center py-2 px-3">우선순위</th>
              <th className="text-center py-2 px-3">상태</th>
              <th className="text-center py-2 px-3">재시도</th>
              <th className="text-left py-2 px-3">등록 시각</th>
              <th className="text-center py-2 px-3">액션</th>
            </tr>
          </thead>
          <tbody>
            {items.map(item => {
              const meta = statusMeta[item.status] || statusMeta['PENDING']
              return (
                <tr key={item.id} className="border-b border-edge/50 hover:bg-edge/30">
                  <td className="py-2 px-3 text-gray-500 font-mono text-xs">{item.id}</td>
                  <td className="py-2 px-3 text-brand font-mono text-xs">{item.deviceId}</td>
                  <td className="py-2 px-3 text-gray-300 text-xs">{item.locationCode || '-'}</td>
                  <td className="py-2 px-3 text-white text-xs">{item.productName || item.productCode}</td>
                  <td className="py-2 px-3 text-right font-mono text-xs">
                    {item.newPrice?.toLocaleString()}원
                    {item.newSalePrice && item.newSalePrice !== item.newPrice && (
                      <span className="ml-1 text-red-400">→ {item.newSalePrice.toLocaleString()}원</span>
                    )}
                  </td>
                  <td className="py-2 px-3 text-center">
                    <span className={`text-xs font-mono ${item.priority <= 2 ? 'text-red-400' : 'text-gray-400'}`}>
                      P{item.priority}
                    </span>
                  </td>
                  <td className="py-2 px-3 text-center">
                    <span className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded border ${meta.color}`}>
                      {meta.icon} {meta.label}
                    </span>
                  </td>
                  <td className="py-2 px-3 text-center text-xs text-gray-400">
                    {item.retryCount}/{item.maxRetry}
                  </td>
                  <td className="py-2 px-3 text-xs text-gray-500">
                    {new Date(item.createdAt).toLocaleString()}
                  </td>
                  <td className="py-2 px-3 text-center">
                    {['PENDING', 'FAILED'].includes(item.status) && (
                      <button
                        onClick={() => cancelMut.mutate(item.id)}
                        className="text-xs text-gray-500 hover:text-red-400 px-2 py-0.5 rounded bg-edge"
                      >취소</button>
                    )}
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
        {items.length === 0 && (
          <div className="text-center text-gray-500 py-12">업데이트 큐가 비어있습니다.</div>
        )}
      </div>
    </div>
  )
}
