import { useState, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useProductCache } from '../hooks/useProductCache'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'

// ── Heart icon ────────────────────────────────────────────────────────────────
function Heart({ filled, size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? '#ef4444' : 'none'} stroke={filled ? '#ef4444' : 'currentColor'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  )
}

// ── Thumb (product image or initials) ─────────────────────────────────────────
function Thumb({ product, size = 42, radius = 10 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: radius, flexShrink: 0,
      background: 'var(--bg3)', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {product.image_url
        ? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        : <span style={{ fontSize: Math.round(size * 0.33), fontWeight: 700, color: 'var(--muted)' }}>
            {product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
          </span>
      }
    </div>
  )
}

// ── Item Favorites Modal ───────────────────────────────────────────────────────
// Shows all attribute sections with heart toggles.
// The waiter picks which items appear in that product's Favorites tab.

function AttrSection({ title, items, favIds, onToggle }) {
  if (!items || items.length === 0) return null
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{
        fontSize: 11, fontWeight: 700, color: 'var(--muted)',
        textTransform: 'uppercase', letterSpacing: 0.8,
        padding: '0 0 8px',
      }}>
        {title}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
        {items.map(item => {
          const isFav = favIds.includes(item.id)
          return (
            <div
              key={item.id}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 14px',
                background: isFav ? 'rgba(239,68,68,0.07)' : 'var(--bg2)',
                border: `1px solid ${isFav ? 'rgba(239,68,68,0.25)' : 'var(--border)'}`,
                borderRadius: 10,
                transition: 'background 120ms, border-color 120ms',
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {item.name}
                </div>
                {item.extra_cost != null && item.extra_cost !== 0 && (
                  <div style={{ fontSize: 12, color: 'var(--muted)' }}>+{Number(item.extra_cost).toFixed(2)} €</div>
                )}
                {item.price != null && item.price !== 0 && (
                  <div style={{ fontSize: 12, color: 'var(--muted)' }}>+{Number(item.price).toFixed(2)} €</div>
                )}
              </div>
              <button
                onClick={() => onToggle(item.id)}
                style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, flexShrink: 0, color: isFav ? '#ef4444' : 'var(--muted)' }}
              >
                <Heart filled={isFav} size={20} />
              </button>
            </div>
          )
        })}
      </div>
    </div>
  )
}

function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
  // Local state: { quick: id[], ingredients: id[], options: id[], prefs: id[] }
  // Start from waiter overrides if they exist, otherwise seed from manager's is_favorite flags
  function seedFromManager() {
    return {
      quick:       (product.quick_options  || []).filter(x => x.is_favorite).map(x => x.id),
      ingredients: (product.ingredients    || []).filter(x => x.is_favorite).map(x => x.id),
      options:     (product.options        || []).filter(x => x.is_favorite).map(x => x.id),
      prefs:       (product.preference_sets|| []).filter(x => x.is_favorite).map(x => x.id),
    }
  }

  const [local, setLocal] = useState(() => waiterAttrFavs ?? seedFromManager())

  const hasAnything = (
    (product.quick_options   || []).length > 0 ||
    (product.ingredients     || []).length > 0 ||
    (product.options         || []).length > 0 ||
    (product.preference_sets || []).length > 0
  )

  function toggle(section, id) {
    setLocal(prev => {
      const arr = prev[section] || []
      return {
        ...prev,
        [section]: arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id],
      }
    })
  }

  const totalSelected = (local.quick?.length || 0) + (local.ingredients?.length || 0) + (local.options?.length || 0) + (local.prefs?.length || 0)

  function handleSave() {
    // If nothing selected, clear the override (fall back to manager)
    const isEmpty = totalSelected === 0
    onSave(isEmpty ? null : local)
    onClose()
  }

  function handleClear() {
    setLocal({ quick: [], ingredients: [], options: [], prefs: [] })
  }

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100 }}
      />

      {/* Sheet */}
      <div style={{
        position: 'fixed', left: 0, right: 0, bottom: 0,
        zIndex: 101,
        background: 'var(--bg)',
        borderRadius: '20px 20px 0 0',
        maxHeight: '88vh',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -8px 40px rgba(0,0,0,0.2)',
      }}>
        {/* Handle bar */}
        <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 0' }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--border)' }} />
        </div>

        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 16px 12px', borderBottom: '1px solid var(--border)', flexShrink: 0,
        }}>
          <Thumb product={product} size={38} radius={9} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {product.name}
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>
              {waiterAttrFavs ? 'Προσωπικές ρυθμίσεις ενεργές' : 'Χρήση ρυθμίσεων διαχειριστή'}
            </div>
          </div>
          <button
            onClick={onClose}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, fontSize: 20, lineHeight: 1 }}
          >
            ✕
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 0' }}>
          {!hasAnything ? (
            <p style={{ color: 'var(--muted)', fontSize: 14, textAlign: 'center', padding: '32px 0' }}>
              Αυτό το προϊόν δεν έχει επιλογές, υλικά ή προτιμήσεις.
            </p>
          ) : (
            <>
              <p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 16, lineHeight: 1.5 }}>
                Επίλεξε ποιες επιλογές θα εμφανίζονται στην καρτέλα <strong style={{ color: '#ef4444' }}>♥ Αγαπημένα</strong> για αυτό το προϊόν. Αν δεν επιλέξεις τίποτα, θα χρησιμοποιηθούν οι ρυθμίσεις του διαχειριστή.
              </p>

              <AttrSection
                title="Γρήγορες Επιλογές"
                items={product.quick_options}
                favIds={local.quick || []}
                onToggle={id => toggle('quick', id)}
              />
              <AttrSection
                title="Υλικά"
                items={product.ingredients}
                favIds={local.ingredients || []}
                onToggle={id => toggle('ingredients', id)}
              />
              <AttrSection
                title="Extras"
                items={product.options}
                favIds={local.options || []}
                onToggle={id => toggle('options', id)}
              />
              <AttrSection
                title="Προτιμήσεις"
                items={product.preference_sets}
                favIds={local.prefs || []}
                onToggle={id => toggle('prefs', id)}
              />
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{
          display: 'flex', gap: 10, padding: '12px 16px',
          borderTop: '1px solid var(--border)', flexShrink: 0,
          paddingBottom: 'max(12px, env(safe-area-inset-bottom))',
        }}>
          {waiterAttrFavs && (
            <button
              onClick={handleClear}
              style={{
                padding: '0 16px', height: 44, borderRadius: 12,
                border: '1.5px solid var(--border)',
                background: 'var(--bg2)', color: 'var(--muted)',
                fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}
            >
              Επαναφορά
            </button>
          )}
          <button
            onClick={handleSave}
            style={{
              flex: 1, height: 44, borderRadius: 12, border: 'none',
              background: totalSelected > 0 ? '#ef4444' : 'var(--accent)',
              color: '#fff',
              fontSize: 15, fontWeight: 700, cursor: 'pointer',
            }}
          >
            {totalSelected > 0 ? `Αποθήκευση (${totalSelected} επιλογές)` : 'Αποθήκευση'}
          </button>
        </div>
      </div>
    </>
  )
}

// ── Product row (ALL tab) ─────────────────────────────────────────────────────
function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs }) {
  const hasAttrs = (
    (product.quick_options   || []).length > 0 ||
    (product.ingredients     || []).length > 0 ||
    (product.options         || []).length > 0 ||
    (product.preference_sets || []).length > 0
  )

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 16px', borderBottom: '1px solid var(--border)',
    }}>
      <Thumb product={product} />

      {/* Tappable area — opens attr editor */}
      <div
        onClick={hasAttrs ? () => onEditAttrs(product) : undefined}
        style={{ flex: 1, minWidth: 0, cursor: hasAttrs ? 'pointer' : 'default' }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {product.name}
          </div>
          {hasAttrOverride && (
            <Heart filled size={12} />
          )}
        </div>
        <div style={{ fontSize: 12, color: hasAttrs ? 'var(--accent)' : 'var(--muted)' }}>
          {hasAttrs ? 'Επιλογές αγαπημένων →' : `${Number(product.base_price).toFixed(2)} €`}
        </div>
      </div>

      {/* Heart — toggles product in/out of favorites list */}
      <button
        onClick={() => onToggleFav(product.id)}
        style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 6, color: isFav ? '#ef4444' : 'var(--muted)', flexShrink: 0 }}
      >
        <Heart filled={isFav} />
      </button>
    </div>
  )
}

// ── Draggable favorites list (pointer-events — works on touch + mouse) ─────────
function FavoritesList({ items, products, onReorder }) {
  const [dragging, setDragging]   = useState(null)
  const [dropIndex, setDropIndex] = useState(null)
  const containerRef = useRef(null)
  const stateRef     = useRef({ dragging: null, dropIndex: null })

  function getProductById(id) { return products.find(p => p.id === id) }

  function computeDropIndex(clientY) {
    if (!containerRef.current) return null
    const rows = [...containerRef.current.querySelectorAll('[data-drag-row]')]
    for (let i = 0; i < rows.length; i++) {
      const rect = rows[i].getBoundingClientRect()
      if (clientY < rect.top + rect.height * 0.51) return i
    }
    return rows.length
  }

  const onPointerDown = useCallback((e, idx) => {
    e.currentTarget.setPointerCapture(e.pointerId)
    stateRef.current = { dragging: idx, dropIndex: null }
    setDragging(idx)

    function onMove(ev) {
      const di = computeDropIndex(ev.clientY)
      if (di !== stateRef.current.dropIndex) {
        stateRef.current.dropIndex = di
        setDropIndex(di)
      }
    }

    function onUp() {
      const { dragging: from, dropIndex: to } = stateRef.current
      if (from != null && to != null) {
        const next = [...items]
        const [moved] = next.splice(from, 1)
        const insertAt = to > from ? to - 1 : to
        next.splice(insertAt, 0, moved)
        onReorder(next)
      }
      stateRef.current = { dragging: null, dropIndex: null }
      setDragging(null)
      setDropIndex(null)
      window.removeEventListener('pointermove', onMove)
      window.removeEventListener('pointerup', onUp)
    }

    window.addEventListener('pointermove', onMove)
    window.addEventListener('pointerup', onUp)
  }, [items, onReorder])

  if (items.length === 0) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flex: 1, padding: 32, gap: 12 }}>
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.4 }}>
          <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
        </svg>
        <p style={{ fontSize: 14, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.6 }}>
          Δεν έχεις προσθέσει αγαπημένα ακόμα.<br />Πήγαινε στην καρτέλα ΌΛΑ και πάτα την καρδιά δίπλα στα προϊόντα.
        </p>
      </div>
    )
  }

  return (
    <div ref={containerRef} style={{ flex: 1, overflowY: 'auto', touchAction: 'pan-x' }}>
      {dropIndex === 0 && dragging != null && (
        <div style={{ height: 3, background: '#22c55e', margin: '0 16px', borderRadius: 2 }} />
      )}

      {items.map((productId, idx) => {
        const product = getProductById(productId)
        if (!product) return null
        const isDragging = dragging === idx
        return (
          <div key={productId}>
            <div
              data-drag-row
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '11px 16px',
                borderBottom: '1px solid var(--border)',
                background: isDragging ? 'var(--bg3)' : 'var(--bg)',
                opacity: isDragging ? 0.45 : 1,
                transition: 'opacity 120ms',
                userSelect: 'none', WebkitUserSelect: 'none',
              }}
            >
              <div
                onPointerDown={e => onPointerDown(e, idx)}
                style={{
                  color: 'var(--muted)', flexShrink: 0,
                  display: 'flex', flexDirection: 'column', gap: 2.5, padding: '6px 4px',
                  cursor: 'grab', touchAction: 'none',
                }}
              >
                {[0,1,2].map(i => <span key={i} style={{ display: 'block', width: 16, height: 2.5, background: 'currentColor', borderRadius: 1 }} />)}
              </div>

              <Thumb product={product} size={38} radius={9} />

              <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {product.name}
              </span>

              <span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>{Number(product.base_price).toFixed(2)} €</span>
            </div>

            {dropIndex === idx + 1 && dragging != null && dragging !== idx && (
              <div style={{ height: 3, background: '#22c55e', margin: '0 16px', borderRadius: 2 }} />
            )}
          </div>
        )
      })}
    </div>
  )
}

// ── Main page ─────────────────────────────────────────────────────────────────
export default function FavoritesSetupPage() {
  const navigate = useNavigate()
  const { products, categories } = useProductCache()
  const { favorites, toggleFavorite, reorderFavorites, itemFavorites, setItemFavorites } = useWaiterFavoritesStore()
  const [tab, setTab] = useState('all')
  const [editingProduct, setEditingProduct] = useState(null)  // product object for ItemFavoritesModal

  const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)

  return (
    <div className="page" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Header */}
      <header className="top-bar">
        <button className="icon-btn" onClick={() => navigate(-1)}>←</button>
        <span className="top-bar__title">Ρύθμιση Αγαπημένων</span>
        <div style={{ width: 40 }} />
      </header>

      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', flexShrink: 0, background: 'var(--bg)' }}>
        {[
          { key: 'all', label: 'ΌΛΑ' },
          { key: 'favorites', label: `ΑΓΑΠΗΜΈΝΑ (${favorites.length})` },
        ].map(t => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            style={{
              flex: 1, padding: '12px 8px',
              background: 'none', border: 'none', cursor: 'pointer',
              fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
              color: tab === t.key ? 'var(--accent)' : 'var(--muted)',
              borderBottom: `2.5px solid ${tab === t.key ? 'var(--accent)' : 'transparent'}`,
              transition: 'color 120ms, border-color 120ms',
            }}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
        {tab === 'all' ? (
          topLevel.map(cat => {
            const subcats = categories.filter(c => c.parent_id === cat.id)
            const directProds = products.filter(p => p.category_id === cat.id && p.is_available)
            const subProds = subcats.flatMap(sc => products.filter(p => p.category_id === sc.id && p.is_available))
            const allProds = [...directProds, ...subProds]
            if (allProds.length === 0) return null
            return (
              <div key={cat.id}>
                <div style={{
                  padding: '8px 16px', fontSize: 11, fontWeight: 700,
                  color: cat.color || 'var(--muted)',
                  textTransform: 'uppercase', letterSpacing: 0.8,
                  background: 'var(--bg2)', borderBottom: '1px solid var(--border)',
                  position: 'sticky', top: 0, zIndex: 1,
                }}>
                  {cat.name}
                </div>
                {allProds.map(p => (
                  <ProductRow
                    key={p.id}
                    product={p}
                    isFav={favorites.includes(p.id)}
                    hasAttrOverride={!!itemFavorites[p.id]}
                    onToggleFav={toggleFavorite}
                    onEditAttrs={setEditingProduct}
                  />
                ))}
              </div>
            )
          })
        ) : (
          <FavoritesList
            items={favorites}
            products={products}
            onReorder={reorderFavorites}
          />
        )}
      </div>

      {/* Item attribute favorites modal */}
      {editingProduct && (
        <ItemFavoritesModal
          product={editingProduct}
          waiterAttrFavs={itemFavorites[editingProduct.id] ?? null}
          onSave={attrFavs => setItemFavorites(editingProduct.id, attrFavs)}
          onClose={() => setEditingProduct(null)}
        />
      )}
    </div>
  )
}
