import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CheckCircle, XCircle, MinusCircle } from 'lucide-react'
import { getPosCvt, processPosCvt, ignorePosCvt } from '../api/client'

export default function PosCvtList() {
  const qc = useQueryClient()
  const [status, setStatus] = useState('PENDING')
  const [keyword, setKeyword] = useState('')

  const { data: items = [], isLoading } = useQuery({
    queryKey: ['pos-cvt', status, keyword],
    queryFn:  () => getPosCvt({ status: status || undefined, keyword: keyword || undefined }),
  })

  const processMut = useMutation({
    mutationFn: processPosCvt,
    onSuccess:  () => qc.invalidateQueries({ queryKey: ['pos-cvt'] }),
  })
  const ignoreMut = useMutation({
    mutationFn: ignorePosCvt,
    onSuccess:  () => qc.invalidateQueries({ queryKey: ['pos-cvt'] }),
  })

  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">POS 가격 변환</h1>
        <div className="flex gap-2">
          <input value={keyword} onChange={e => setKeyword(e.target.value)}
            placeholder="상품코드·상품명 검색"
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300 w-48" />
          <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">
            {['','PENDING','PROCESSED','ERROR','IGNORED'].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-3 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(items as any[]).map((p: any) => (
              <tr key={p.id} className="border-b border-edge hover:bg-edge/30">
                <td className="px-3 py-3 text-brand text-xs">{p.tenantCode}</td>
                <td className="px-3 py-3 text-gray-300 text-xs">{p.storeName || '-'}</td>
                <td className="px-3 py-3 text-gray-300 font-mono text-xs">{p.productCode}</td>
                <td className="px-3 py-3 text-white text-xs">{p.productName}</td>
                <td className="px-3 py-3 text-gray-300 text-xs">{p.price?.toLocaleString()}</td>
                <td className="px-3 py-3 text-accent text-xs">{p.salePrice?.toLocaleString()}</td>
                <td className="px-3 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${
                    p.status === 'PROCESSED' ? 'bg-green-500/20 text-green-400' :
                    p.status === 'PENDING'   ? 'bg-yellow-500/20 text-yellow-400' :
                    p.status === 'ERROR'     ? 'bg-red-500/20 text-red-400' :
                    'bg-gray-500/20 text-gray-400'
                  }`}>{p.status}</span>
                </td>
                <td className="px-3 py-3 text-gray-500 text-xs">
                  {p.createdAt ? new Date(p.createdAt).toLocaleString('ko-KR') : '-'}
                </td>
                <td className="px-3 py-3">
                  {p.status === 'PENDING' && (
                    <div className="flex gap-2">
                      <button onClick={() => processMut.mutate(p.id)} title="처리" className="text-green-400 hover:text-green-300">
                        <CheckCircle size={14} />
                      </button>
                      <button onClick={() => ignoreMut.mutate(p.id)} title="무시" className="text-gray-400 hover:text-gray-300">
                        <MinusCircle size={14} />
                      </button>
                    </div>
                  )}
                </td>
              </tr>
            ))}
            {(items as any[]).length === 0 && (
              <tr><td colSpan={9} className="px-4 py-8 text-center text-gray-500">데이터가 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
