import { useState } from 'react'
import OrderDrawer from './OrderDrawer'

function CategoriesIcon({ width = 20, height = 20 }) {
  return (
    <svg width={width} height={height} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <rect x="14" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <rect x="3" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  )
}

const API_URL = import.meta.env.VITE_API_URL || ''

function hexToRgba(hex, alpha) {
  if (!hex) return null
  const h = hex.replace('#', '')
  const r = parseInt(h.substring(0, 2), 16)
  const g = parseInt(h.substring(2, 4), 16)
  const b = parseInt(h.substring(4, 6), 16)
  return `rgba(${r},${g},${b},${alpha})`
}

function ProductGrid({ products, onOpen }) {
  if (products.length === 0) return null
  return (
    <div className="product-grid">
      {products.map(product => {
        const initials = product.name
          .trim()
          .split(/\s+/)
          .slice(0, 2)
          .map(w => w[0])
          .join('')
          .toUpperCase()
        return (
          <button key={product.id} className="product-btn" onClick={() => onOpen(product)}>
            <div className="product-btn__thumb">
              <div className="product-btn__thumb-inner">
                {product.image_url
                  ? <img src={`${API_URL}${product.image_url}`} alt="" className="product-btn__img" />
                  : <span className="product-btn__initials">{initials}</span>
                }
              </div>
            </div>
            <div className="product-btn__info">
              <span className="product-btn__name">{product.name}</span>
              <span className="product-btn__price">{Number(product.base_price).toFixed(2)} €</span>
            </div>
          </button>
        )
      })}
    </div>
  )
}

// Builds the ordered list of sections for a top-level category:
// interleaves direct products (as a "General" section) and sub-categories
// according to general_sort_order and each sub's sort_order.
function buildSections(parent, subcategories, directProducts) {
  const sections = []

  if (directProducts.length > 0) {
    sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts })
  }

  for (const sub of subcategories) {
    sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order })
  }

  return sections.sort((a, b) => a.sort_order - b.sort_order)
}

export default function ProductPicker({ categories, products, onAdd, viewAllOpen, setViewAllOpen }) {
  const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
  const initialCatId = topLevel[0]?.id ?? null
  const [activeCat, setActiveCat] = useState(initialCatId)
  const [drawerProduct, setDrawerProduct] = useState(null)
  // Track which sub-category sections are expanded (by sub-cat id or '__general__')
  const [expandedSubs, setExpandedSubs] = useState(() => {
    if (!initialCatId) return {}
    const subs = categories.filter(c => c.parent_id === initialCatId)
    const state = {}
    subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true })
    return state
  })

  const activeParent = categories.find(c => c.id === activeCat)
  const subcategories = activeParent
    ? categories.filter(c => c.parent_id === activeCat).sort((a, b) => a.sort_order - b.sort_order)
    : []
  const hasSubcats = subcategories.length > 0

  // Products directly on this top-level category (no sub-cat)
  const directProducts = products.filter(p => p.category_id === activeCat)
  // Products for the flat view (no sub-cats)
  const flatProducts = products.filter(p => p.category_id === activeCat)

  // Build sections for accordion view
  const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : []

  function buildDefaultExpanded(catId) {
    const subs = categories.filter(c => c.parent_id === catId)
    const state = {}
    subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true })
    return state
  }

  function selectCategory(id) {
    setActiveCat(id)
    setViewAllOpen(false)
    setExpandedSubs(buildDefaultExpanded(id))
  }

  function toggleSub(key) {
    setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] }))
  }

  function openDrawer(product) { setDrawerProduct(product) }
  function closeDrawer() { setDrawerProduct(null) }

  return (
    <div className="product-picker">
      <div className="category-tabs">
        <div className="category-tabs__scroll-wrap">
          <div className="category-tabs__scroll">
          {topLevel.map(cat => {
            const isActive = activeCat === cat.id
            const bg = cat.color
              ? isActive ? cat.color : hexToRgba(cat.color, 0.35)
              : isActive ? 'var(--accent)' : 'var(--bg3)'
            const color = cat.color
              ? isActive ? '#fff' : 'rgba(255,255,255,0.65)'
              : isActive ? 'var(--accent-fg)' : 'var(--muted)'
            return (
              <button
                key={cat.id}
                className="cat-tab"
                style={{ background: bg, color, border: isActive && cat.color ? `2px solid ${cat.color}` : undefined }}
                onClick={() => selectCategory(cat.id)}
              >
                {cat.name}
              </button>
            )
          })}
          </div>
        </div>
      </div>

      {/* Product area — flat grid or accordion depending on sub-cats */}
      <div className="product-area">
        {!hasSubcats ? (
          // No sub-categories: original flat grid
          <>
            <ProductGrid products={flatProducts} onOpen={openDrawer} />
            {flatProducts.length === 0 && (
              <p style={{ color: '#64748b', textAlign: 'center', padding: 32 }}>
                Δεν υπάρχουν προϊόντα
              </p>
            )}
          </>
        ) : (
          // Has sub-categories: accordion view
          <div className="subcat-accordion">
            {sections.map(section => {
              const key = section._isGeneral ? '__general__' : String(section.id)
              const isOpen = !!expandedSubs[key]
              const sectionProducts = section._isGeneral
                ? section.products
                : products.filter(p => p.category_id === section.id)
              if (sectionProducts.length === 0) return null

              // General products appear flat — no collapsible header
              if (section._isGeneral) {
                return (
                  <div key={key} className="subcat-general">
                    <ProductGrid products={sectionProducts} onOpen={openDrawer} />
                  </div>
                )
              }

              const accentColor = section.color ?? activeParent?.color ?? null

              return (
                <div key={key} className="subcat-section">
                  <button
                    className={`subcat-header ${isOpen ? 'subcat-header--open' : ''}`}
                    onClick={() => toggleSub(key)}
                  >
                    {accentColor && <span className="subcat-header__pill" style={{ background: accentColor }} />}
                    <span className="subcat-header__name">{section.name}</span>
                    <span className="subcat-header__count">{sectionProducts.length}</span>
                    <svg
                      className="subcat-header__chevron"
                      style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}
                      width="16" height="16" viewBox="0 0 24 24" fill="none"
                    >
                      <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </button>

                  {isOpen && (
                    <div className="subcat-body">
                      <ProductGrid products={sectionProducts} onOpen={openDrawer} />
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* View All modal — top-level categories only */}
      {viewAllOpen && (
        <div className="modal-overlay" onClick={() => setViewAllOpen(false)}>
          <div
            className="cat-all-modal"
            onClick={e => e.stopPropagation()}
          >
            <div className="cat-all-modal__header">
              <span className="cat-all-modal__title">Κατηγορίες</span>
              <button className="icon-btn" onClick={() => setViewAllOpen(false)}>✕</button>
            </div>
            <div className="cat-all-grid">
              {topLevel.map(cat => {
                const isActive = activeCat === cat.id
                const bg = cat.color || 'var(--bg3)'
                const overlay = isActive ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.35)'
                return (
                  <button
                    key={cat.id}
                    className={`cat-all-tile ${isActive ? 'cat-all-tile--active' : ''}`}
                    style={{ background: bg, boxShadow: isActive ? `0 0 0 3px #fff` : undefined }}
                    onClick={() => selectCategory(cat.id)}
                  >
                    <span className="cat-all-tile__overlay" style={{ background: overlay }} />
                    <span className="cat-all-tile__name">{cat.name}</span>
                  </button>
                )
              })}
            </div>
          </div>
        </div>
      )}

      <OrderDrawer
        product={drawerProduct}
        isOpen={!!drawerProduct}
        onClose={closeDrawer}
        onAdd={item => { onAdd(item); closeDrawer() }}
      />
    </div>
  )
}
