import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Flower2, Search, Plus, Pencil, Trash2, X } from 'lucide-react'
import {
  getProducts, getProduct, getCategories, createProduct, updateProduct, deleteProduct, setProductStatus,
} from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

const STATUSES = ['ON_SALE', 'SOLD_OUT', 'HIDDEN']
const OCCASIONS = ['', 'BIRTHDAY', 'ANNIVERSARY', 'SYMPATHY', 'LOVE', 'CONGRATS', 'GET_WELL', 'THANK_YOU']
const FLOWERS = ['', 'ROSES', 'TULIPS', 'LILIES', 'ORCHIDS', 'SUNFLOWERS', 'MIXED']

type SizeRow = { sizeCode: string; label: string; price: string; stemCount: string }

const EMPTY = {
  id: 0, categoryId: '', sku: '', name: '', brand: '', description: '',
  price: '', salePrice: '', status: 'ON_SALE', stock: '0', thumbnail: '',
  occasion: '', flowerType: '', shelfLifeDays: '5',
  sizes: [] as SizeRow[],
}

export default function Products() {
  const qc = useQueryClient()
  const [kw, setKw] = useState('')
  const [open, setOpen] = useState(false)
  const [form, setForm] = useState<any>({ ...EMPTY })
  const [err, setErr] = useState('')
  const [saving, setSaving] = useState(false)

  const { data } = useQuery({ queryKey: ['admin-products', kw], queryFn: () => getProducts({ keyword: kw, size: 100, status: '' }) })
  const { data: cats } = useQuery({ queryKey: ['admin-cats'], queryFn: getCategories })
  const items = data?.items || []
  const categories = cats || []

  const refresh = () => qc.invalidateQueries({ queryKey: ['admin-products'] })

  const cycle = async (id: number, status: string) => {
    const next = status === 'ON_SALE' ? 'HIDDEN' : 'ON_SALE'
    await setProductStatus(id, next).catch(() => {}); refresh()
  }

  const openNew = () => { setForm({ ...EMPTY }); setErr(''); setOpen(true) }

  const openEdit = async (id: number) => {
    setErr('')
    const p = await getProduct(id).catch(() => null)
    if (!p) return
    setForm({
      id: p.id, categoryId: p.categoryId ?? '', sku: p.sku ?? '', name: p.name ?? '', brand: p.brand ?? '',
      description: p.description ?? '', price: String(p.price ?? ''), salePrice: p.salePrice != null ? String(p.salePrice) : '',
      status: p.status || 'ON_SALE', stock: String(p.stock ?? 0), thumbnail: p.thumbnail ?? '',
      occasion: p.occasion ?? '', flowerType: p.flowerType ?? '', shelfLifeDays: String(p.shelfLifeDays ?? 5),
      sizes: (p.sizes || []).map((s: any) => ({ sizeCode: s.sizeCode || '', label: s.label || '', price: String(s.price ?? ''), stemCount: String(s.stemCount ?? '') })),
    })
    setOpen(true)
  }

  const addSize = () => setForm((f: any) => ({ ...f, sizes: [...f.sizes, { sizeCode: 'ORIGINAL', label: '', price: '', stemCount: '' }] }))
  const setSize = (i: number, k: string, v: string) => setForm((f: any) => ({ ...f, sizes: f.sizes.map((s: SizeRow, idx: number) => idx === i ? { ...s, [k]: v } : s) }))
  const delSize = (i: number) => setForm((f: any) => ({ ...f, sizes: f.sizes.filter((_: SizeRow, idx: number) => idx !== i) }))

  const save = async () => {
    if (!form.name.trim()) { setErr('Product name is required.'); return }
    if (form.price === '' || isNaN(Number(form.price))) { setErr('A valid price is required.'); return }
    setSaving(true); setErr('')
    const payload: any = {
      categoryId: form.categoryId === '' ? null : Number(form.categoryId),
      sku: form.sku.trim() || null, name: form.name.trim(), brand: form.brand.trim() || null,
      description: form.description.trim() || null, price: Number(form.price),
      salePrice: form.salePrice === '' ? null : Number(form.salePrice),
      status: form.status, stock: form.stock === '' ? 0 : Number(form.stock),
      thumbnail: form.thumbnail.trim() || null, occasion: form.occasion || null,
      flowerType: form.flowerType || null, shelfLifeDays: form.shelfLifeDays === '' ? 5 : Number(form.shelfLifeDays),
      sizes: form.sizes
        .filter((s: SizeRow) => s.sizeCode && s.price !== '')
        .map((s: SizeRow, i: number) => ({
          sizeCode: s.sizeCode, label: s.label || s.sizeCode, price: Number(s.price),
          stemCount: s.stemCount === '' ? null : Number(s.stemCount), sortOrder: i,
        })),
    }
    try {
      if (form.id) await updateProduct(form.id, payload)
      else await createProduct(payload)
      setOpen(false); refresh()
    } catch {
      setErr('Failed to save the product. Please check the inputs.')
    } finally { setSaving(false) }
  }

  const remove = async (id: number, name: string) => {
    if (!window.confirm(`Delete product "${name}"? This cannot be undone.`)) return
    await deleteProduct(id).catch(() => {}); refresh()
  }

  const fld = 'bg-panel border border-edge rounded-lg px-3 py-2 text-sm'

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><Flower2 className="text-brand" size={22} /><h1 className="text-xl font-bold">상품 관리</h1></div>
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-2 bg-card border border-edge rounded-lg px-3 py-2">
            <Search size={15} className="text-slate-500" />
            <input value={kw} onChange={e => setKw(e.target.value)} placeholder="상품 검색" className="bg-transparent text-sm outline-none w-48" />
          </div>
          <button onClick={openNew} className="flex items-center gap-1.5 bg-brand text-ink text-sm font-semibold px-3 py-2 rounded-lg"><Plus size={15} /> New Product</button>
        </div>
      </div>

      {open && (
        <div className="fixed inset-0 z-50 bg-black/60 flex items-start justify-center overflow-y-auto p-4" onClick={() => !saving && setOpen(false)}>
          <div className="bg-card border border-edge rounded-xl p-5 w-full max-w-2xl mt-8 space-y-3" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-bold">{form.id ? 'Edit Product' : 'New Product'}</h2>
              <button onClick={() => setOpen(false)} className="text-slate-400 hover:text-slate-200"><X size={18} /></button>
            </div>
            {err && <div className="text-xs text-rose-400 bg-rose-500/10 border border-rose-500/30 rounded-lg px-3 py-2">{err}</div>}
            <div className="grid grid-cols-3 gap-3">
              <input value={form.sku} onChange={e => setForm({ ...form, sku: e.target.value })} placeholder="SKU" className={fld} />
              <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Product Name *" className={`${fld} col-span-2`} />
            </div>
            <div className="grid grid-cols-3 gap-3">
              <select value={form.categoryId} onChange={e => setForm({ ...form, categoryId: e.target.value })} className={fld}>
                <option value="">Category</option>
                {categories.map((c: any) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
              <input value={form.brand} onChange={e => setForm({ ...form, brand: e.target.value })} placeholder="Brand" className={fld} />
              <select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })} className={fld}>
                {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
            <textarea value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} placeholder="Description" rows={2} className={`${fld} w-full`} />
            <div className="grid grid-cols-4 gap-3">
              <input type="number" value={form.price} onChange={e => setForm({ ...form, price: e.target.value })} placeholder="Price *" className={fld} />
              <input type="number" value={form.salePrice} onChange={e => setForm({ ...form, salePrice: e.target.value })} placeholder="Sale Price" className={fld} />
              <input type="number" value={form.stock} onChange={e => setForm({ ...form, stock: e.target.value })} placeholder="Stock" className={fld} />
              <input type="number" value={form.shelfLifeDays} onChange={e => setForm({ ...form, shelfLifeDays: e.target.value })} placeholder="Shelf Life (days)" className={fld} />
            </div>
            <div className="grid grid-cols-3 gap-3">
              <select value={form.occasion} onChange={e => setForm({ ...form, occasion: e.target.value })} className={fld}>
                {OCCASIONS.map(o => <option key={o} value={o}>{o || 'Occasion'}</option>)}
              </select>
              <select value={form.flowerType} onChange={e => setForm({ ...form, flowerType: e.target.value })} className={fld}>
                {FLOWERS.map(o => <option key={o} value={o}>{o || 'Flower Type'}</option>)}
              </select>
              <input value={form.thumbnail} onChange={e => setForm({ ...form, thumbnail: e.target.value })} placeholder="Thumbnail URL" className={fld} />
            </div>

            <div className="border border-edge rounded-lg p-3 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-semibold text-slate-300">Sizes (Original / Deluxe / Grand)</span>
                <button onClick={addSize} className="text-xs flex items-center gap-1 text-brand"><Plus size={12} /> Add Size</button>
              </div>
              {form.sizes.length === 0 && <p className="text-xs text-slate-500">No size variants. Base price is used.</p>}
              {form.sizes.map((s: SizeRow, i: number) => (
                <div key={i} className="grid grid-cols-12 gap-2 items-center">
                  <select value={s.sizeCode} onChange={e => setSize(i, 'sizeCode', e.target.value)} className={`${fld} col-span-3`}>
                    {['ORIGINAL', 'DELUXE', 'GRAND'].map(c => <option key={c}>{c}</option>)}
                  </select>
                  <input value={s.label} onChange={e => setSize(i, 'label', e.target.value)} placeholder="Label" className={`${fld} col-span-3`} />
                  <input type="number" value={s.price} onChange={e => setSize(i, 'price', e.target.value)} placeholder="Price" className={`${fld} col-span-3`} />
                  <input type="number" value={s.stemCount} onChange={e => setSize(i, 'stemCount', e.target.value)} placeholder="Stems" className={`${fld} col-span-2`} />
                  <button onClick={() => delSize(i)} className="col-span-1 text-rose-400 flex justify-center"><Trash2 size={14} /></button>
                </div>
              ))}
            </div>

            <div className="flex items-center justify-end gap-2 pt-1">
              <button onClick={() => setOpen(false)} disabled={saving} className="border border-edge text-slate-400 text-sm px-4 py-2 rounded-lg">Cancel</button>
              <button onClick={save} disabled={saving} className="bg-brand text-ink font-semibold text-sm px-5 py-2 rounded-lg disabled:opacity-50">{saving ? 'Saving…' : (form.id ? 'Update' : 'Create')}</button>
            </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">SKU</th><th className="text-left">상품명</th><th className="text-left">상황</th>
            <th className="text-right">가격</th><th className="text-right">재고</th><th className="text-right">판매</th><th className="text-right">평점</th><th className="text-center">상태</th><th className="text-center">관리</th>
          </tr></thead>
          <tbody>
            {items.map((p: any) => (
              <tr key={p.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 font-mono text-xs text-slate-400">{p.sku}</td>
                <td>{p.name}</td>
                <td className="text-slate-400">{p.occasion || '-'}</td>
                <td className="text-right">{money(p.salePrice && p.salePrice > 0 ? p.salePrice : p.price)}</td>
                <td className="text-right text-slate-400">{p.stock}</td>
                <td className="text-right text-slate-400">{p.salesCount}</td>
                <td className="text-right text-amber-400">{p.ratingAvg?.toFixed(1) || '-'}</td>
                <td className="text-center"><button onClick={() => cycle(p.id, p.status)}><StatusBadge status={p.status} /></button></td>
                <td className="text-center">
                  <div className="inline-flex gap-1">
                    <button onClick={() => openEdit(p.id)} title="Edit" className="text-xs bg-panel border border-edge text-slate-300 px-2 py-1 rounded inline-flex items-center gap-1"><Pencil size={12} /></button>
                    <button onClick={() => remove(p.id, p.name)} title="Delete" className="text-xs bg-rose-500/15 text-rose-400 px-2 py-1 rounded inline-flex items-center gap-1"><Trash2 size={12} /></button>
                  </div>
                </td>
              </tr>
            ))}
            {!items.length && <tr><td colSpan={9} className="text-center text-slate-500 py-8">상품이 없습니다.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
