import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, X } from 'lucide-react'
import { getProducts, createProduct, updateProduct, deleteProduct } from '../api/client'

export default function ProductList() {
  const qc = useQueryClient()
  const [keyword, setKeyword] = useState('')
  const [modal, setModal] = useState<any>(null)

  const { data: products = [], isLoading } = useQuery({
    queryKey: ['products', keyword],
    queryFn:  () => getProducts({ keyword: keyword || undefined }),
  })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateProduct(d.id, d) : createProduct(d),
    onSuccess:  () => { qc.invalidateQueries({ queryKey: ['products'] }); setModal(null) },
  })

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

  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">
          <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" />
          <button onClick={() => setModal({})}
            className="flex items-center gap-1.5 bg-brand hover:bg-brand2 text-white px-3 py-1.5 rounded text-sm">
            <Plus size={14} /> 상품 추가
          </button>
        </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>
            {(products 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-400 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">{p.productName}</td>
                <td className="px-3 py-3 text-gray-400 text-xs">{p.category}</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 font-medium">{p.salePrice?.toLocaleString()}</td>
                <td className="px-3 py-3 text-gray-500 text-xs">{p.currency}</td>
                <td className="px-3 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${p.active ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'}`}>
                    {p.active ? '활성' : '비활성'}
                  </span>
                </td>
                <td className="px-3 py-3">
                  <div className="flex gap-2">
                    <button onClick={() => setModal(p)} className="text-brand hover:text-blue-300"><Edit size={14} /></button>
                    <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(p.id) }}
                      className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
            {(products as any[]).length === 0 && (
              <tr><td colSpan={10} className="px-4 py-8 text-center text-gray-500">상품이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {modal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-card border border-edge rounded-lg p-6 w-full max-w-md">
            <div className="flex justify-between mb-4">
              <h2 className="font-semibold">{modal.id ? '상품 수정 / 가격 변경' : '상품 추가'}</h2>
              <button onClick={() => setModal(null)}><X size={16} /></button>
            </div>
            <ProductForm initial={modal} onSave={(d: any) => saveMut.mutate(d)} />
          </div>
        </div>
      )}
    </div>
  )
}

function ProductForm({ initial, onSave }: { initial: any; onSave: (d: any) => void }) {
  const [f, setF] = useState({
    tenantCode:  initial.tenantCode  || 'EMART',
    storeId:     initial.storeId     ?? '',
    productCode: initial.productCode || '',
    productName: initial.productName || '',
    category:    initial.category    || '',
    price:       initial.price       ?? '',
    salePrice:   initial.salePrice   ?? '',
    currency:    initial.currency    || 'KRW',
    active:      initial.active !== false,
    id:          initial.id,
  })
  const set = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
    setF(p => ({ ...p, [k]: e.target.value }))

  const submit = (e: React.FormEvent) => {
    e.preventDefault()
    onSave({
      ...f,
      storeId:   f.storeId === '' ? null : Number(f.storeId),
      price:     f.price === '' ? null : Number(f.price),
      salePrice: f.salePrice === '' ? null : Number(f.salePrice),
      active:    f.active === true || (f as any).active === 'true',
    })
  }

  return (
    <form onSubmit={submit} className="space-y-3">
      <div>
        <label className="block text-xs text-gray-400 mb-1">테넌트</label>
        <select value={f.tenantCode} onChange={set('tenantCode')}
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white">
          {['TENANT_A','TENANT_B','EMART','ZIOINFO'].map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>
      {[
        { label: '매장 ID',   key: 'storeId',     type: 'number', ph: '예: 1' },
        { label: '상품코드',  key: 'productCode' },
        { label: '상품명',    key: 'productName' },
        { label: '카테고리',  key: 'category' },
        { label: '정가',      key: 'price',       type: 'number' },
        { label: '판매가',    key: 'salePrice',   type: 'number' },
      ].map(({ label, key, type, ph }) => (
        <div key={key}>
          <label className="block text-xs text-gray-400 mb-1">{label}</label>
          <input type={type || 'text'} value={(f as any)[key]} onChange={set(key)} placeholder={ph}
            className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white" />
        </div>
      ))}
      <div>
        <label className="block text-xs text-gray-400 mb-1">화폐</label>
        <select value={f.currency} onChange={set('currency')}
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white">
          {['KRW','USD','EUR'].map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>
      <div>
        <label className="block text-xs text-gray-400 mb-1">상태</label>
        <select value={String(f.active)} onChange={set('active')}
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white">
          <option value="true">활성</option>
          <option value="false">비활성</option>
        </select>
      </div>
      <button type="submit" className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm">
        저장
      </button>
    </form>
  )
}
