import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowLeftRight, Sparkles } from 'lucide-react'
import { getTransfers, approveTransfer, rejectTransfer, getStores, aiTransferRecommend } from '../api/client'
import StatusBadge from '../components/StatusBadge'

export default function Transfers() {
  const qc = useQueryClient()
  const [status, setStatus] = useState('')
  const [recs, setRecs] = useState<any[]>([])
  const { data: transfers } = useQuery({ queryKey: ['transfers', status], queryFn: () => getTransfers(status, '') })
  const { data: stores } = useQuery({ queryKey: ['tr-stores'], queryFn: () => getStores(false) })

  const approve = async (id: number) => { await approveTransfer(id).catch(() => {}); qc.invalidateQueries({ queryKey: ['transfers'] }) }
  const reject = async (id: number) => { await rejectTransfer(id).catch(() => {}); qc.invalidateQueries({ queryKey: ['transfers'] }) }
  const aiSuggest = async () => {
    const ids = (stores || []).map((s: any) => s.id)
    const r = await aiTransferRecommend(ids).catch(() => [])
    setRecs(r || [])
  }
  const storeName = (id: number) => stores?.find((s: any) => s.id === id)?.code || `#${id}`

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><ArrowLeftRight className="text-brand" size={22} /><h1 className="text-xl font-bold">Inventory Transfers</h1></div>
        <div className="flex items-center gap-2">
          <button onClick={aiSuggest} className="flex items-center gap-1.5 bg-brand2 text-white text-sm px-3 py-2 rounded-lg"><Sparkles size={14} /> AI Transfer Suggestions</button>
          <select value={status} onChange={e => setStatus(e.target.value)} className="bg-card border border-edge rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>{['REQUESTED', 'APPROVED', 'REJECTED', 'COMPLETED'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      {!!recs.length && (
        <div className="bg-card border border-edge rounded-xl p-4 mb-5">
          <div className="text-xs text-brand mb-2 flex items-center gap-1.5"><Sparkles size={12} /> AI Recommended Transfers</div>
          <div className="space-y-1.5 text-sm">
            {recs.map((r, i) => (
              <div key={i} className="flex items-center justify-between text-slate-300">
                <span>Product #{r.productId}: {storeName(r.fromStoreId)} → {storeName(r.toStoreId)} ×{r.suggestedQty}</span>
                <span className="text-xs text-slate-500">{r.reason}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">ID</th><th className="text-left">From → To</th><th className="text-left">Product</th><th className="text-right">Quantity</th><th className="text-left">Reason</th><th className="text-center">Status</th><th className="text-center">Actions</th>
          </tr></thead>
          <tbody>
            {(transfers || []).map((t: any) => (
              <tr key={t.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 text-slate-400">{t.id}</td>
                <td>{storeName(t.fromStoreId)} → {storeName(t.toStoreId)}</td>
                <td className="text-slate-400">#{t.productId}{t.aiRecommended && <span className="ml-1 text-[10px] text-brand">AI</span>}</td>
                <td className="text-right">{t.quantity}</td>
                <td className="text-slate-400 text-xs">{t.reason}</td>
                <td className="text-center"><StatusBadge status={t.status} /></td>
                <td className="text-center">
                  {t.status === 'REQUESTED' && (<div className="inline-flex gap-1">
                    <button onClick={() => approve(t.id)} className="text-xs bg-emerald-500/15 text-emerald-400 px-2 py-1 rounded">Approve</button>
                    <button onClick={() => reject(t.id)} className="text-xs bg-rose-500/15 text-rose-400 px-2 py-1 rounded">Reject</button>
                  </div>)}
                </td>
              </tr>
            ))}
            {!(transfers || []).length && <tr><td colSpan={7} className="text-center text-slate-500 py-8">No transfer requests.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
