const { h, preactHooks, matter } = globalThis.ami
const { useState, useEffect } = preactHooks
const { Popup } = matter

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: [
    'Tandem 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 AdminDashboard () {
  const [products, setProducts] = useState([])
  const [filteredProducts, setFilteredProducts] = useState([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editingProduct, setEditingProduct] = useState(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [filterBrand, setFilterBrand] = useState('')
  const [filterMainCategory, setFilterMainCategory] = useState('')
  const [filterSubcategory, setFilterSubcategory] = useState('')

  // Check authentication
  useEffect(() => {
    const token = localStorage.getItem('adminToken')
    if (!token) {
      globalThis.location.href = '/admin/login'
      return
    }
    loadProducts()
  }, [])

  // Filter products
  useEffect(() => {
    let filtered = products
    if (searchTerm) {
      filtered = filtered.filter(p =>
        p.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        p.brand?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }
    if (filterMainCategory) {
      filtered = filtered.filter(p => p.mainCategory === filterMainCategory)
    }
    if (filterSubcategory) {
      filtered = filtered.filter(p => p.subcategory === filterSubcategory)
    }
    if (filterBrand) {
      filtered = filtered.filter(p => p.brand === filterBrand)
    }
    setFilteredProducts(filtered)
  }, [products, searchTerm, filterBrand, filterMainCategory, filterSubcategory])

  const loadProducts = async () => {
    try {
      // First try to fetch from API (Vercel KV or updated source)
      let data = []
      try {
        const apiResponse = await fetch('/api/admin/products')
        if (apiResponse.ok) {
          data = await apiResponse.json()
        }
      } catch (error) {
        // Ignore API fetch error, fallback to static file
      }

      // If no data from API, load from static JSON file (default/initial data)
      if (!data || data.length === 0) {
        const response = await fetch('/assets/products.json')
        data = await response.json()
      }

      setProducts(data)
      setFilteredProducts(data)
    } catch (error) {
      console.error('Failed to load products:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    localStorage.removeItem('adminToken')
    localStorage.removeItem('adminUser')

    try {
      // Optional: Call logout API to clear server-side session if exists
      await fetch('/api/admin/logout', {
        method: 'POST',
        headers: { Authorization: `Bearer ${localStorage.getItem('adminToken')}` }
      })
    } catch (error) {
      // Ignore errors on logout
    }

    globalThis.location.href = '/admin/login'
  }

  const handleAddProduct = () => {
    setEditingProduct({
      title: '',
      text: '',
      subcategory: '',
      brand: '',
      mainCategory: '',
      image: { src: '', alt: '', width: 295, height: 295 },
      links: [{ name: 'View product', value: '/all_products.html' }]
    })
    setShowModal(true)
  }

  const handleEditProduct = product => {
    setEditingProduct({ ...product })
    setShowModal(true)
  }

  const handleDeleteProduct = async index => {
    if (!confirm('Are you sure you want to delete this product?')) { return }

    const newProducts = products.filter((_, i) => i !== index)
    await saveProducts(newProducts)
  }

  const handleSaveProduct = async e => {
    e.preventDefault()
    let newProducts

    if (editingProduct.index === undefined) {
      // Add new
      newProducts = [...products, editingProduct]
    } else {
      // Edit existing
      newProducts = [...products]
      newProducts[editingProduct.index] = editingProduct
    }

    await saveProducts(newProducts)
    setShowModal(false)
    setEditingProduct(null)
  }

  const saveProducts = async newProducts => {
    try {
      const response = await fetch('/api/admin/products', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${localStorage.getItem('adminToken')}`
        },
        body: JSON.stringify({ products: newProducts })
      })

      if (response.ok) {
        setProducts(newProducts)
        alert('Products updated successfully!')
        setShowModal(false)
      } else {
        alert('Failed to save products')
      }
    } catch (error) {
      console.error('Save failed:', error)
      alert('Failed to save products')
    }
  }

  const brands = [...new Set(products.map(p => p.brand).filter(Boolean))].sort()
  const mainCategories = [...new Set(products.map(p => p.mainCategory).filter(Boolean))].sort()
  const subcategories = filterMainCategory ? (SUBCATEGORIES[filterMainCategory] || []) : []

  if (loading) {
    return h('div', { className: 'flex items-center justify-center min-h-screen' },
      h('div', { className: 'text-xl' }, 'Loading...')
    )
  }

  return h('div', { className: 'min-h-screen bg-gray-50' },
    // Header
    h('div', { className: 'bg-white shadow' },
      h('div', { className: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4' },
        h('div', { className: 'flex justify-between items-center' },
          h('div', {},
            h('h1', { className: 'text-2xl font-bold text-gray-900' }, 'Product Management'),
            h('p', { className: 'text-sm text-gray-600' }, `Total Products: ${products.length}`)
          ),
          h('button', {
            onClick: handleLogout,
            className: 'px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors'
          }, 'Logout')
        )
      )
    ),

    // Main Content
    h('div', { className: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8' },
      // Filters and Add Button
      h('div', { className: 'bg-white rounded-lg shadow p-6 mb-6' },
        h('div', { className: 'grid grid-cols-1 md:grid-cols-6 gap-4 mb-4' },
          h('input', {
            type: 'text',
            placeholder: 'Search products...',
            className: 'px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500',
            value: searchTerm,
            onInput: e => setSearchTerm(e.target.value)
          }),
          h('select', {
            className: 'px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500',
            value: filterMainCategory,
            onChange: e => {
              setFilterMainCategory(e.target.value)
              setFilterSubcategory('')
            }
          },
          h('option', { value: '' }, 'All Main Categories'),
          mainCategories.map(mainCat => h('option', { value: mainCat, key: mainCat }, mainCat))
          ),
          h('select', {
            className: 'px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500',
            value: filterSubcategory,
            onChange: e => setFilterSubcategory(e.target.value),
            disabled: !filterMainCategory
          },
          h('option', { value: '' }, 'All Subcategories'),
          subcategories.map(subcat => h('option', { value: subcat, key: subcat }, subcat))
          ),
          h('select', {
            className: 'px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500',
            value: filterBrand,
            onChange: e => setFilterBrand(e.target.value)
          },
          h('option', { value: '' }, 'All Brands'),
          brands.map(brand => h('option', { value: brand, key: brand }, brand))
          ),
          h('button', {
            onClick: handleAddProduct,
            className: 'px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-medium'
          }, '+ Add Product')
        ),
        h('p', { className: 'text-sm text-gray-600' }, `Showing ${filteredProducts.length} products`)
      ),

      // Products Table
      h('div', { className: 'bg-white rounded-lg shadow overflow-hidden' },
        h('div', { className: 'overflow-x-auto' },
          h('table', { className: 'min-w-full divide-y divide-gray-200' },
            h('thead', { className: 'bg-gray-50' },
              h('tr', {},
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Image'),
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Title'),
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Brand'),
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Category'),
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Description'),
                h('th', { className: 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider' }, 'Actions')
              )
            ),
            h('tbody', { className: 'bg-white divide-y divide-gray-200' },
              filteredProducts.map((product, index) =>
                h('tr', { key: index, className: 'hover:bg-gray-50' },
                  h('td', { className: 'px-6 py-4 whitespace-nowrap' },
                    h('img', { src: product.image.src, alt: product.image.alt, className: 'h-12 w-12 object-cover rounded' })
                  ),
                  h('td', { className: 'px-6 py-4' },
                    h('div', { className: 'text-sm font-medium text-gray-900' }, product.title)
                  ),
                  h('td', { className: 'px-6 py-4 whitespace-nowrap' },
                    h('span', { className: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800' }, product.brand || 'N/A')
                  ),
                  h('td', { className: 'px-6 py-4 whitespace-nowrap text-sm text-gray-500' }, product.subcategory),
                  h('td', { className: 'px-6 py-4 whitespace-nowrap text-sm text-gray-900' }, product.text),
                  h('td', { className: 'px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2' },
                    h('button', {
                      onClick: () => {
                        const productIndex = products.findIndex(p => p.title === product.title)
                        handleEditProduct({ ...product, index: productIndex })
                      },
                      className: 'text-indigo-600 hover:text-indigo-900'
                    }, 'Edit'),
                    h('button', {
                      onClick: () => {
                        const productIndex = products.findIndex(p => p.title === product.title)
                        handleDeleteProduct(productIndex)
                      },
                      className: 'text-red-600 hover:text-red-900'
                    }, 'Delete')
                  )
                )
              )
            )
          )
        )
      )
    ),

    // Modal popup for Add/Edit using Popup component
    h(Popup, {
      _show: showModal,
      _layout: 'toast',
      onKeyDown: event => event.key === 'Escape' && setShowModal(false)
    },
    h('div', { className: 'flex flex-col h-full bg-white rounded-t-xl' },
      h('div', { className: 'flex justify-between items-center p-4 border-b' },
        h('h2', { className: 'text-xl font-bold' }, editingProduct?.index === undefined ? 'Add New Product' : 'Edit Product'),
        h('button', {
          onClick: () => {
            setShowModal(false)
            setEditingProduct(null)
          },
          className: 'text-gray-500 hover:text-gray-700'
        }, '✕')
      ),
      h('div', { className: 'flex-1 overflow-y-auto p-4' },
        h('form', { onSubmit: handleSaveProduct, className: 'space-y-4' },
          h('div', {},
            h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Title *'),
            h('input', {
              type: 'text',
              required: true,
              className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
              value: editingProduct?.title || '',
              onInput: e => setEditingProduct({ ...editingProduct, title: e.target.value })
            })
          ),
          h('div', { className: 'grid grid-cols-2 gap-4' },
            h('div', {},
              h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Brand *'),
              h('input', {
                type: 'text',
                required: true,
                className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
                value: editingProduct?.brand || '',
                onInput: e => setEditingProduct({ ...editingProduct, brand: e.target.value })
              })
            ),
            h('div', {},
              h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Main Category *'),
              h('select', {
                required: true,
                className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
                value: editingProduct?.mainCategory || '',
                onChange: e => setEditingProduct({
                  ...editingProduct,
                  mainCategory: e.target.value,
                  subcategory: ''
                })
              },
              h('option', { value: '' }, 'Select Main Category'),
              Object.keys(SUBCATEGORIES).map(mainCat => h('option', { value: mainCat, key: mainCat }, mainCat))
              )
            )
          ),
          h('div', {},
            h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Subcategory *'),
            h('select', {
              required: true,
              className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
              value: editingProduct?.subcategory || '',
              onChange: e => setEditingProduct({ ...editingProduct, subcategory: e.target.value }),
              disabled: !editingProduct?.mainCategory
            },
            h('option', { value: '' }, 'Select Subcategory'),
            (editingProduct?.mainCategory ? SUBCATEGORIES[editingProduct.mainCategory] || [] : []).map(subcat =>
              h('option', { value: subcat, key: subcat }, subcat)
            )
            )
          ),
          h('div', {},
            h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Description (3-4 words) *'),
            h('input', {
              type: 'text',
              required: true,
              placeholder: 'e.g. Premium Soft Close',
              className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
              value: editingProduct?.text || '',
              onInput: e => setEditingProduct({ ...editingProduct, text: e.target.value })
            })
          ),
          h('div', {},
            h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Image URL *'),
            h('input', {
              type: 'text',
              required: true,
              placeholder: '/assets/images/hardware/product.jpg',
              className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
              value: editingProduct?.image?.src || '',
              onInput: e => setEditingProduct({
                ...editingProduct,
                image: { ...editingProduct.image, src: e.target.value }
              })
            })
          ),
          h('div', {},
            h('label', { className: 'block text-sm font-medium text-gray-700 mb-1' }, 'Image Alt Text *'),
            h('input', {
              type: 'text',
              required: true,
              placeholder: 'e.g. Soft Close Drawer Slide | Best hardware in Bangalore',
              className: 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500',
              value: editingProduct?.image?.alt || '',
              onInput: e => setEditingProduct({
                ...editingProduct,
                image: { ...editingProduct.image, alt: e.target.value }
              })
            })
          ),
          h('div', { className: 'flex justify-end space-x-3 pt-4' },
            h('button', {
              type: 'button',
              onClick: () => {
                setShowModal(false)
                setEditingProduct(null)
              },
              className: 'px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50'
            }, 'Cancel'),
            h('button', {
              type: 'submit',
              className: 'px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700'
            }, 'Save Product')
          )
        )
      )
    )

  )
  )
}

globalThis.ami.register(AdminDashboard, 'admin-dashboard')
