import PromoWithPopup from '#amidala/wcs/shared/promo-with-popup/promo-with-popup.js'

const { h, register, preactHooks, matter } = globalThis.ami
const { useState, useEffect, useMemo } = preactHooks
const { Box, Button, Input } = matter

const LABELS = {
  SEARCH_TEXT: 'Search',
  ORDER_BY: 'Sort by',
  LOAD_MORE: 'Load more',
  RESET_FILTERS: 'Reset filters',
  ASCENDING: 'ascending',
  DESCENDING: 'descending',
  BACK_TO_OVERVIEW: 'Back to overview',
  PREVIOUS_ITEM: 'Go to the previous item',
  NEXT_ITEM: 'Go to the next item'
}

const SUBCATEGORIES = {
  Sanitaryware: [
    'Showers',
    'Mixer & Diverters',
    'Flushing System',
    'Faucets',
    'Wash Basin',
    'Sinks',
    'Mirror',
    'Bath Tub',
    'Kamod',
    'Toilet Paper Holder',
    'Towel Stand',
    'Shelf & Corner',
    'Hooks',
    'Soap Dispenser',
    'Water Heaters',
    'Washing Machine'
  ],
  Hardware: [
    'Tandom Box',
    'Hinges',
    'Drawer Channel (Normal & Softclose)',
    'Sliding Channel',
    'Handles',
    'Locks (Digital Locks & Normal Locks)',
    'Lockers',
    'Doorclosers',
    'Doorprofiles',
    'Liftup system',
    'Kitchen corners',
    'Pantery Unit',
    'Wardrobe',
    'Door chain',
    'Door Stoper',
    'Door Eyes'
  ],
  'Kitchen Appliances': [
    'Hob & Induction Hob',
    'Chimney',
    'Oven Microwave',
    'Refrigerator',
    'Deep Fryer',
    'Barbeque Grill',
    'Toaster',
    'Electric Kettle',
    'Dishwasher',
    'Juicer Mixer Grinder',
    'Coffee Maker',
    'Warmer Drawer',
    'Cooking Range',
    'Cold Pressed Juicer',
    'Food Waste Disposer'
  ],
  Plywood: [
    'Commercial',
    'Waterproof',
    'Marine',
    'Fire Retardant',
    'Flexible',
    'MDF',
    'Particle Board',
    'Laminates',
    'Veneers',
    'Adhesives',
  ]
}

function Items ({ items }) {
  const models = items.map(item => ({
    image: item.image,
    title: item.title,
    text: item.text, // This is usually the price
    links: [
      { name: 'Brand', value: item.brand || 'Generic' },
      { name: 'Category', value: item.subcategory },
      { name: 'Product', value: item.text },
      { name: 'Description', value: item.description || item.title }
    ]
  }))

  return h('div', { className: 'grid gap-5 grid-cols-4 md:grid-cols-2 sm:grid-cols-1', role: 'list' }, models.map((_m, index) =>
    h(PromoWithPopup, { models, currentModelIndex: index })
  ))
}

function UniversalGallery ({ items = [], src }) {
  const [allItems, setAllItems] = useState([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [mainCategory, setMainCategory] = useState('')
  const [subcategory, setSubcategory] = useState('')
  const [brand, setBrand] = useState('')

  // Load data on mount
  useEffect(() => {
    (async () => {
      try {
        let data = []
        if (items.length) {
          data = items
        } else if (src) {
          const response = await fetch(src)
          if (!response.ok) { throw new Error('Failed to load data') }
          data = await response.json()
        }
        setAllItems(data)
      } catch (error) {
        console.error('Failed to load products:', error)
      } finally {
        setLoading(false)
      }
    })()
  }, [])

  // Parse URL hash on mount and hash change
  useEffect(() => {
    const updateFromHash = () => {
      const hash = globalThis.location.hash.substring(1)
      const params = new URLSearchParams(hash)
      setMainCategory(params.get('mainCategory') || '')
      setSubcategory(params.get('subcategory') || '')
      setBrand(params.get('brand') || '')
      setSearchTerm(params.get('q') || '')
    }

    updateFromHash()
    globalThis.addEventListener('hashchange', updateFromHash)
    return () => globalThis.removeEventListener('hashchange', updateFromHash)
  }, [])

  // Get unique values for dropdowns
  const mainCategories = useMemo(() =>
    [...new Set(allItems.map(p => p.mainCategory).filter(Boolean))].sort(),
  [allItems]
  )

  const availableSubcategories = useMemo(() => {
    if (mainCategory && SUBCATEGORIES[mainCategory]) {
      return SUBCATEGORIES[mainCategory]
    }
    return [...new Set(allItems.map(p => p.subcategory).filter(Boolean))].sort()
  }, [mainCategory, allItems])

  const brands = useMemo(() =>
    [...new Set(allItems.map(p => p.brand).filter(Boolean))].sort(),
  [allItems]
  )

  // Filter items
  const filteredItems = useMemo(() => {
    let result = allItems

    if (searchTerm) {
      const search = searchTerm.toLowerCase()
      result = result.filter(p =>
        p.title?.toLowerCase().includes(search) ||
        p.subcategory?.toLowerCase().includes(search) ||
        p.brand?.toLowerCase().includes(search) ||
        p.description?.toLowerCase().includes(search)
      )
    }

    if (mainCategory) {
      result = result.filter(p => p.mainCategory === mainCategory)
    }

    if (subcategory) {
      result = result.filter(p => p.subcategory === subcategory)
    }

    if (brand) {
      result = result.filter(p => p.brand === brand)
    }

    return result
  }, [allItems, searchTerm, mainCategory, subcategory, brand])

  // Update URL hash
  const updateHash = newFilters => {
    const params = new URLSearchParams()
    if (newFilters.mainCategory || mainCategory) { params.set('mainCategory', newFilters.mainCategory || mainCategory) }
    if (newFilters.subcategory || subcategory) { params.set('subcategory', newFilters.subcategory || subcategory) }
    if (newFilters.brand || brand) { params.set('brand', newFilters.brand || brand) }
    if (newFilters.search || searchTerm) { params.set('q', newFilters.search || searchTerm) }
    globalThis.location.hash = params.toString()
  }

  const handleMainCategoryChange = e => {
    setMainCategory(e.target.value)
    setSubcategory('')
    updateHash({ mainCategory: e.target.value, subcategory: '' })
  }

  const handleSubcategoryChange = e => {
    setSubcategory(e.target.value)
    updateHash({ subcategory: e.target.value })
  }

  const handleBrandChange = e => {
    setBrand(e.target.value)
    updateHash({ brand: e.target.value })
  }

  const handleSearchChange = e => {
    setSearchTerm(e.target.value)
    updateHash({ search: e.target.value })
  }

  const handleResetFilters = () => {
    setSearchTerm('')
    setMainCategory('')
    setSubcategory('')
    setBrand('')
    globalThis.location.hash = ''
  }

  if (loading) {
    return h('div', { className: 'text-center py-8' }, 'Loading...')
  }

  if (!allItems.length) {
    return null
  }

  return h('div', { className: 'space-y-6' },
    // Filter Bar
    h(Box, { className: 'text-txa bg-bga rounded-2xl p-6' },
      h('div', { className: 'grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-6' },
        // Search
        h(Input, {
          _size: 'sm',
          type: 'search',
          name: 'search',
          placeholder: LABELS.SEARCH_TEXT,
          value: searchTerm,
          onInput: handleSearchChange
        }),
        // Main Category
        h(Input, {
          _size: 'sm',
          type: 'select',
          name: 'mainCategory',
          value: mainCategory,
          onChange: handleMainCategoryChange,
          children: [
            h('option', { value: '' }, 'All Main Categories'),
            ...mainCategories.map(cat => h('option', { value: cat }, cat))
          ]
        }),
        // Subcategory
        h(Input, {
          _size: 'sm',
          type: 'select',
          name: 'subcategory',
          value: subcategory,
          onChange: handleSubcategoryChange,
          disabled: !mainCategory,
          children: [
            h('option', { value: '' }, 'All Subcategories'),
            ...availableSubcategories.map(subcat => h('option', { value: subcat }, subcat))
          ]
        }),
        // Brand
        h(Input, {
          _size: 'sm',
          type: 'select',
          name: 'brand',
          value: brand,
          onChange: handleBrandChange,
          children: [
            h('option', { value: '' }, 'All Brands'),
            ...brands.map(b => h('option', { value: b }, b))
          ]
        }),
        // Reset
        h(Button, {
          _model: { name: LABELS.RESET_FILTERS },
          onClick: handleResetFilters,
          className: 'px-4 py-2'
        })
      ),
      h('p', { className: 'text-sm text-gray-600 mt-4' }, `Showing ${filteredItems.length} products`)
    ),
    // Items
    h(Items, { items: filteredItems })
  )
}

register(UniversalGallery, 'universal-gallery')
