import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Link2, Link2Off, MapPin, Battery, Wifi, WifiOff, RefreshCw } from 'lucide-react'
import api from '../api/client'

interface TagBinding {
  id: number; tenantCode: string; storeId: number; storeName: string
  deviceId: string; productCode: string; productName: string
  locationCode: string; templateCode: string; lastPrice: number
  lastUpdatedAt: string; bindStatus: string
  deviceStatus: string; batteryLevel: number; signalStrength: string
  createdAt: string
}

interface BindForm {
  tenantCode: string; storeId: string; deviceId: string
  productCode: string; locationCode: string; templateCode: string
}

const bindStatusColor: Record<string, string> = {
  ACTIVE:  'text-green-400 bg-green-500/10 border-green-500/30',
  UNBOUND: 'text-gray-400 bg-gray-500/10 border-gray-500/30',
  ERROR:   'text-red-400 bg-red-500/10 border-red-500/30',
}

const deviceStatusIcon = (s: string) =>
  s === 'ONLINE' ? <Wifi size={13} className="text-green-400" /> : <WifiOff size={13} className="text-red-400" />

export default function TagBindingList() {
  const qc = useQueryClient()
  const [tenantCode, setTenantCode] = useState('')
  const [storeId, setStoreId]       = useState('')
  const [keyword, setKeyword]       = useState('')
  const [showForm, setShowForm]     = useState(false)
  const [form, setForm]             = useState<BindForm>({
    tenantCode:'', storeId:'', deviceId:'', productCode:'', locationCode:'', templateCode:'EM-PRICE-STD'
  })

  const { data: bindings = [], isLoading } = useQuery<TagBinding[]>({
    queryKey: ['tag-binding', tenantCode, storeId, keyword],
    queryFn: () => api.get('/tag-binding', { params: {
      tenantCode: tenantCode || undefined,
      storeId: storeId || undefined,
      keyword: keyword || undefined,
      bindStatus: 'ACTIVE',
    }}).then(r => r.data.data),
    refetchInterval: 20000,
  })

  const bindMut = useMutation({
    mutationFn: (data: BindForm) => api.post('/tag-binding', {
      ...data,
      storeId: Number(data.storeId),
    }),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['tag-binding'] }); setShowForm(false) },
  })

  const unbindMut = useMutation({
    mutationFn: (id: number) => api.put(`/tag-binding/${id}/unbind`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tag-binding'] }),
  })

  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>
        <button
          onClick={() => setShowForm(v => !v)}
          className="flex items-center gap-2 px-3 py-1.5 bg-brand text-white rounded text-sm"
        >
          <Link2 size={14} /> 바인딩 추가
        </button>
      </div>

      {/* 바인딩 추가 폼 */}
      {showForm && (
        <div className="bg-panel border border-edge rounded-lg p-4 space-y-3">
          <h2 className="text-sm font-medium text-white">e-paper 태그 → 상품 바인딩</h2>
          <div className="grid grid-cols-3 gap-3">
            {[
              { key:'tenantCode',    label:'테넌트', ph:'EMART' },
              { key:'storeId',       label:'매장ID', ph:'1' },
              { key:'deviceId',      label:'태그 Device ID', ph:'ESL-EM-001-0001' },
              { key:'productCode',   label:'상품코드', ph:'P-001' },
              { key:'locationCode',  label:'선반 위치코드', ph:'A01-03' },
              { key:'templateCode',  label:'템플릿', ph:'EM-PRICE-STD' },
            ].map(({ key, label, ph }) => (
              <div key={key}>
                <label className="text-xs text-gray-400 mb-1 block">{label}</label>
                <input
                  value={form[key as keyof BindForm]}
                  onChange={e => setForm(f => ({ ...f, [key]: e.target.value }))}
                  placeholder={ph}
                  className="w-full bg-edge border border-gray-600 rounded px-2 py-1.5 text-sm text-white"
                />
              </div>
            ))}
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => bindMut.mutate(form)}
              className="px-3 py-1.5 bg-brand text-white rounded text-sm"
            >바인딩 저장</button>
            <button onClick={() => setShowForm(false)} className="px-3 py-1.5 bg-edge text-gray-300 rounded text-sm">취소</button>
          </div>
        </div>
      )}

      {/* 필터 */}
      <div className="flex gap-3">
        {[
          { val: tenantCode, set: setTenantCode, ph: '테넌트 필터' },
          { val: keyword,    set: setKeyword,    ph: '태그ID / 상품코드 / 위치 검색' },
        ].map(({ val, set, ph }, i) => (
          <input key={i} value={val} onChange={e => set(e.target.value)} placeholder={ph}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-300 w-64"
          />
        ))}
      </div>

      {/* 태그 목록 */}
      <div className="grid grid-cols-1 gap-3">
        {bindings.map(b => (
          <div key={b.id}
            className={`bg-panel border rounded-lg p-4 flex items-center justify-between
              ${b.deviceStatus === 'ONLINE' ? 'border-green-500/20' : 'border-red-500/20'}`}
          >
            <div className="flex items-center gap-4">
              {/* 태그 상태 */}
              <div className="flex flex-col items-center gap-1 w-16">
                {deviceStatusIcon(b.deviceStatus)}
                {b.batteryLevel !== null && (
                  <div className="flex items-center gap-1 text-xs text-gray-400">
                    <Battery size={11} />
                    <span className={b.batteryLevel < 20 ? 'text-red-400' : ''}>{b.batteryLevel}%</span>
                  </div>
                )}
              </div>

              {/* 태그 정보 */}
              <div>
                <div className="text-xs font-mono text-brand">{b.deviceId}</div>
                <div className="flex items-center gap-2 mt-1">
                  <MapPin size={11} className="text-gray-500" />
                  <span className="text-xs text-gray-400">{b.locationCode || '위치 미지정'}</span>
                  <span className="text-xs text-gray-600">|</span>
                  <span className="text-xs text-gray-300">{b.storeName}</span>
                </div>
              </div>

              {/* 상품 정보 */}
              <div className="ml-4 pl-4 border-l border-edge">
                <div className="text-sm text-white">{b.productName || b.productCode}</div>
                <div className="text-xs text-gray-400 mt-0.5">
                  현재가: <span className="text-brand font-mono">
                    {b.lastPrice ? b.lastPrice.toLocaleString() + '원' : '미전송'}
                  </span>
                  {b.lastUpdatedAt && (
                    <span className="ml-2 text-gray-600">
                      갱신: {new Date(b.lastUpdatedAt).toLocaleString()}
                    </span>
                  )}
                </div>
                <div className="text-xs text-gray-500 mt-0.5">템플릿: {b.templateCode}</div>
              </div>
            </div>

            {/* 상태 + 액션 */}
            <div className="flex items-center gap-3">
              <span className={`text-xs px-2 py-0.5 rounded border ${bindStatusColor[b.bindStatus] || ''}`}>
                {b.bindStatus}
              </span>
              <button
                onClick={() => { if (confirm(`태그 ${b.deviceId} 언바인딩하겠습니까?`)) unbindMut.mutate(b.id) }}
                className="p-1.5 rounded bg-edge text-gray-400 hover:text-red-400"
                title="언바인딩"
              >
                <Link2Off size={14} />
              </button>
            </div>
          </div>
        ))}
        {bindings.length === 0 && (
          <div className="text-center text-gray-500 py-12">
            바인딩된 태그가 없습니다. 우측 상단 "바인딩 추가"를 클릭하세요.
          </div>
        )}
      </div>
    </div>
  )
}
