'use client'

import { useState, useEffect } from 'react'
import * as XLSX from 'xlsx'

interface ExcelProduct {
  'Product Name': string
  'Product URL': string
  'Product Image': string
  'Price (EUR)': number
  'Product Color': string
  'Product Size': string
  'Product Type': string
}

interface ParsedProduct {
  id: number
  name: string
  price: number
  images: string[]
  category: string
  description: string
  sizes: string[]
  colors: { name: string; hex: string }[]
  discount?: number
}

const categoryMapping: { [key: string]: string } = {
  'Dresses': 'dresses',
  'Lingerie': 'underwear',
  'Tops': 'clothing',
  'Swimwear': 'swimwear',
  'Sportswear': 'sportswear',
  'Leggings': 'sportswear',
  'Sport': 'sportswear',
  'Accessories': 'accessories',
}

const colorMapping: { [key: string]: string } = {
  'Black': '#000000',
  'White': '#FFFFFF',
  'Red': '#FF0000',
  'Pink': '#F8D9E0',
  'Beige': '#F5DEB3',
  'Gold': '#FFD700',
  'Orange': '#FFA500',
}

export default function AdminPage() {
  const [products, setProducts] = useState<ParsedProduct[]>([])
  const [importStatus, setImportStatus] = useState<string>('')
  const [uploadStatus, setUploadStatus] = useState<string>('')
  const [selectedProductId, setSelectedProductId] = useState<number | null>(null)
  const [uploadingImages, setUploadingImages] = useState(false)
  const [editingPrice, setEditingPrice] = useState<number | null>(null)
  const [priceInputValue, setPriceInputValue] = useState<string>('')
  const [editingName, setEditingName] = useState<number | null>(null)
  const [nameInputValue, setNameInputValue] = useState<string>('')

  // Load existing products on mount
  useEffect(() => {
    fetch('/api/products')
      .then(res => res.json())
      .then(data => {
        // Convert existing products to ParsedProduct format
        const existingProducts: ParsedProduct[] = data.map((p: any) => ({
          id: p.id,
          name: p.name,
          price: p.price,
          images: p.images || [],
          category: p.category || 'clothing',
          description: p.description || '',
          sizes: p.sizes || [],
          colors: p.colors || [],
          discount: p.discount
        }))
        setProducts(existingProducts)
      })
      .catch(err => {
        console.error('Error loading products:', err)
      })
  }, [])

  const parseColorString = (colorStr: string): { name: string; hex: string }[] => {
    if (!colorStr) return [{ name: 'Черно', hex: '#000000' }]
    
    const colors = colorStr.split(',').map(c => c.trim())
    return colors.map(color => ({
      name: color,
      hex: colorMapping[color] || '#000000'
    }))
  }

  const mapCategory = (productType: string): string => {
    return categoryMapping[productType] || 'clothing'
  }

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setImportStatus('Четене на файл...')

    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData: ExcelProduct[] = XLSX.utils.sheet_to_json(worksheet)

        setImportStatus(`Намерени ${jsonData.length} продукта. Обработване...`)

        // Get existing products to find the highest ID
        const existingProductsResponse = await fetch('/api/products')
        const existingProducts: ParsedProduct[] = await existingProductsResponse.json()
        
        // Find the highest ID in existing products
        const maxId = existingProducts.length > 0 
          ? Math.max(...existingProducts.map(p => p.id))
          : 0

        // Parse new products starting from maxId + 1
        const parsedProducts: ParsedProduct[] = jsonData.map((row, index) => {
          const colors = parseColorString(row['Product Color'] || 'Black')
          const category = mapCategory(row['Product Type'] || 'Dresses')
          
          return {
            id: maxId + index + 1, // Continue from highest existing ID
            name: row['Product Name'] || `Продукт ${maxId + index + 1}`,
            price: parseFloat(row['Price (EUR)']?.toString() || '0'),
            images: [], // Images will be uploaded separately
            category: category,
            description: `${row['Product Name'] || 'Продукт'} - Висококачествен продукт.`,
            sizes: ['S', 'M', 'L', 'XL'],
            colors: colors.length > 0 ? colors : [{ name: 'Черно', hex: '#000000' }],
          }
        })

        // Merge existing products with new products
        const mergedProducts = [...existingProducts, ...parsedProducts]

        setProducts(mergedProducts)
        
        // Automatically save merged products to JSON file
        try {
          const saveResponse = await fetch('/api/products', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(mergedProducts)
          })
          
          if (saveResponse.ok) {
            setImportStatus(`Успешно добавени ${parsedProducts.length} нови продукта! Общо: ${mergedProducts.length} продукта. Автоматично запазени в products.json.`)
          } else {
            setImportStatus(`Успешно добавени ${parsedProducts.length} нови продукта! Общо: ${mergedProducts.length} продукта. ВАЖНО: Натиснете "Запази в products.json" за да запазите промените.`)
          }
        } catch (saveError) {
          console.error('Error auto-saving products:', saveError)
          setImportStatus(`Успешно добавени ${parsedProducts.length} нови продукта! Общо: ${mergedProducts.length} продукта. ВАЖНО: Натиснете "Запази в products.json" за да запазите промените.`)
        }
      } catch (error) {
        console.error('Error parsing Excel:', error)
        setImportStatus('Грешка при четене на файла. Моля, проверете формата.')
      }
    }

    reader.readAsArrayBuffer(file)
  }

  const saveProductsToJSON = async () => {
    try {
      const response = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(products)
      })
      
      if (response.ok) {
        setImportStatus(`Успешно запазени ${products.length} продукта в products.json!`)
      } else {
        setImportStatus('Грешка при запазване на продуктите.')
      }
    } catch (error) {
      console.error('Error saving products:', error)
      setImportStatus('Грешка при запазване на продуктите.')
    }
  }

  const downloadProductsJSON = async () => {
    // Get the latest products from server before downloading
    try {
      const response = await fetch('/api/products')
      const latestProducts = await response.json()
      const jsonStr = JSON.stringify(latestProducts, null, 2)
      const blob = new Blob([jsonStr], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'products.json'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      setImportStatus('products.json файлът е изтеглен!')
    } catch (error) {
      console.error('Error downloading products:', error)
      setImportStatus('Грешка при изтегляне на файла.')
    }
  }

  const copyToClipboard = () => {
    const jsonStr = JSON.stringify(products, null, 2)
    navigator.clipboard.writeText(jsonStr)
    setImportStatus('JSON копиран в клипборда!')
  }

  const handleDeleteProduct = async (productId: number, productName: string) => {
    if (!confirm(`Сигурни ли сте, че искате да изтриете продукт #${productId}: "${productName}"?\n\nТова ще изтрие продукта и всички негови изображения!`)) {
      return
    }

    try {
      const response = await fetch('/api/delete-product', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productId })
      })

      const result = await response.json()

      if (result.success) {
        // Remove product from state
        setProducts(prevProducts => prevProducts.filter(p => p.id !== productId))
        setImportStatus(`Продукт #${productId} "${productName}" е изтрит успешно! ${result.deletedImages} изображения са изтрити.`)
      } else {
        setImportStatus(`Грешка: ${result.error}`)
      }
    } catch (error) {
      console.error('Error deleting product:', error)
      setImportStatus('Грешка при изтриване на продукта.')
    }
  }

  const handlePriceEdit = (productId: number, currentPrice: number | null) => {
    setEditingPrice(productId)
    setPriceInputValue(currentPrice?.toString() || '0')
  }

  const handlePriceSave = async (productId: number) => {
    const newPrice = parseFloat(priceInputValue)
    if (isNaN(newPrice) || newPrice < 0) {
      setImportStatus('Грешка: Моля, въведете валидна цена!')
      setEditingPrice(null)
      return
    }

    try {
      // Update products state
      const updatedProducts = products.map(p =>
        p.id === productId ? { ...p, price: newPrice } : p
      )
      setProducts(updatedProducts)

      // Save to JSON file
      const response = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedProducts)
      })

      if (response.ok) {
        setImportStatus(`Цената на продукт #${productId} е обновена успешно!`)
      } else {
        setImportStatus('Грешка при запазване на цената.')
      }

      setEditingPrice(null)
    } catch (error) {
      console.error('Error saving price:', error)
      setImportStatus('Грешка при запазване на цената.')
      setEditingPrice(null)
    }
  }

  const handlePriceCancel = () => {
    setEditingPrice(null)
    setPriceInputValue('')
  }

  const handleNameEdit = (productId: number, currentName: string) => {
    setEditingName(productId)
    setNameInputValue(currentName)
  }

  const handleNameSave = async (productId: number) => {
    const newName = nameInputValue.trim()
    if (!newName) {
      setImportStatus('Грешка: Името на продукта не може да бъде празно!')
      setEditingName(null)
      return
    }

    try {
      // Update products state
      const updatedProducts = products.map(p =>
        p.id === productId ? { ...p, name: newName } : p
      )
      setProducts(updatedProducts)

      // Save to JSON file
      const response = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedProducts)
      })

      if (response.ok) {
        setImportStatus(`Името на продукт #${productId} е обновено успешно!`)
      } else {
        setImportStatus('Грешка при запазване на името.')
      }

      setEditingName(null)
    } catch (error) {
      console.error('Error saving name:', error)
      setImportStatus('Грешка при запазване на името.')
      setEditingName(null)
    }
  }

  const handleNameCancel = () => {
    setEditingName(null)
    setNameInputValue('')
  }

  const handleDeleteImage = async (productId: number, imageFilename: string) => {
    if (!confirm(`Сигурни ли сте, че искате да изтриете ${imageFilename}?`)) {
      return
    }

    try {
      const response = await fetch('/api/delete-image', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productId, imageFilename })
      })

      const result = await response.json()

      if (result.success) {
        // Update products state
        setProducts(prevProducts =>
          prevProducts.map(p =>
            p.id === productId
              ? { ...p, images: p.images.filter(img => img !== imageFilename) }
              : p
          )
        )
        setUploadStatus(`Изображението ${imageFilename} е изтрито успешно!`)
      } else {
        setUploadStatus(`Грешка: ${result.error}`)
      }
    } catch (error) {
      console.error('Error deleting image:', error)
      setUploadStatus('Грешка при изтриване на изображението.')
    }
  }

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>, productId: number) => {
    const files = e.target.files
    if (!files || files.length === 0) return

    setUploadingImages(true)
    setUploadStatus(`Качване на ${files.length} изображения за продукт ${productId}...`)

    const formData = new FormData()
    Array.from(files).forEach((file, index) => {
      formData.append('images', file)
    })
    formData.append('productId', productId.toString())

    try {
      const response = await fetch('/api/upload-images', {
        method: 'POST',
        body: formData,
      })

      const result = await response.json()
      
      if (result.success) {
        // Update products state with new image filenames
        const updatedProducts = products.map(p => 
          p.id === productId 
            ? { ...p, images: [...(p.images || []), ...result.images] }
            : p
        )
        setProducts(updatedProducts)
        
        // Save updated products to JSON file
        fetch('/api/products', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(updatedProducts)
        })
        .then(() => {
          setUploadStatus(`Успешно качени ${result.images.length} изображения и запазени в products.json!`)
        })
        .catch(err => {
          console.error('Error saving to products.json:', err)
          setUploadStatus(`Изображенията са качени, но има проблем при запазване в products.json`)
        })
        
        e.target.value = '' // Reset input
      } else {
        setUploadStatus(`Грешка: ${result.error}`)
      }
    } catch (error) {
      console.error('Error uploading images:', error)
      setUploadStatus('Грешка при качване на изображения.')
    } finally {
      setUploadingImages(false)
    }
  }

  return (
    <div className="min-h-screen bg-[#F5F5F5]">
      <header className="bg-white border-b border-gray-200">
        <div className="max-w-4xl mx-auto px-4 py-4">
          <h1 className="text-2xl font-bold text-dark-grey">Админ панел - Импорт на продукти</h1>
        </div>
      </header>

      <div className="max-w-4xl mx-auto px-4 py-8">
        <div className="bg-white rounded-lg p-6 mb-6">
          <h2 className="text-lg font-semibold text-dark-grey mb-4">Импорт от Excel файл</h2>
          
          <div className="mb-4">
            <label className="block text-sm font-medium text-dark-grey mb-2">
              Изберете Excel файл (.xlsx, .xls)
            </label>
            <input
              type="file"
              accept=".xlsx,.xls"
              onChange={handleFileUpload}
              className="block w-full text-sm text-medium-grey file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-light-pink file:text-dark-grey hover:file:bg-opacity-80"
            />
          </div>


          {importStatus && (
            <div className={`p-3 rounded-lg mb-4 ${
              importStatus.includes('Грешка') 
                ? 'bg-red-50 text-red-700' 
                : 'bg-green-50 text-green-700'
            }`}>
              {importStatus}
            </div>
          )}

          {products.length > 0 && (
            <div className="flex gap-3 flex-wrap">
              <button
                onClick={saveProductsToJSON}
                className="px-4 py-2 bg-dark-grey text-white font-semibold rounded-lg hover:bg-opacity-90 transition"
              >
                Запази в products.json
              </button>
              <button
                onClick={downloadProductsJSON}
                className="px-4 py-2 border-2 border-dark-grey text-dark-grey font-semibold rounded-lg hover:bg-gray-50 transition"
              >
                Изтегли products.json
              </button>
              <button
                onClick={copyToClipboard}
                className="px-4 py-2 border-2 border-dark-grey text-dark-grey font-semibold rounded-lg hover:bg-gray-50 transition"
              >
                Копирай JSON
              </button>
            </div>
          )}
        </div>

        {products.length > 0 && (
          <div className="bg-white rounded-lg p-6">
            <h2 className="text-lg font-semibold text-dark-grey mb-4">
              Преглед на продукти ({products.length})
            </h2>
            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="border-b border-gray-200">
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">ID</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Име</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Цена</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Категория</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Изображения</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Цветове</th>
                    <th className="text-left py-2 px-3 text-sm font-medium text-dark-grey">Действия</th>
                  </tr>
                </thead>
                <tbody>
                  {products.slice(0, 10).map((product) => (
                    <tr key={product.id} className="border-b border-gray-100 hover:bg-gray-50">
                      <td className="py-2 px-3 text-sm text-medium-grey">{product.id}</td>
                      <td className="py-2 px-3 text-sm text-dark-grey">
                        {editingName === product.id ? (
                          <div className="flex items-center gap-2">
                            <input
                              type="text"
                              value={nameInputValue}
                              onChange={(e) => setNameInputValue(e.target.value)}
                              className="flex-1 px-2 py-1 border border-gray-300 rounded text-sm"
                              autoFocus
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  handleNameSave(product.id)
                                } else if (e.key === 'Escape') {
                                  handleNameCancel()
                                }
                              }}
                            />
                            <button
                              onClick={() => handleNameSave(product.id)}
                              className="px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
                              title="Запази"
                            >
                              ✓
                            </button>
                            <button
                              onClick={handleNameCancel}
                              className="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500"
                              title="Отказ"
                            >
                              ×
                            </button>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2">
                            <span>{product.name}</span>
                            <button
                              onClick={() => handleNameEdit(product.id, product.name)}
                              className="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition"
                              title="Редактирай име"
                            >
                              ✎
                            </button>
                          </div>
                        )}
                      </td>
                      <td className="py-2 px-3 text-sm text-medium-grey">
                        {editingPrice === product.id ? (
                          <div className="flex items-center gap-2">
                            <input
                              type="number"
                              step="0.01"
                              min="0"
                              value={priceInputValue}
                              onChange={(e) => setPriceInputValue(e.target.value)}
                              className="w-20 px-2 py-1 border border-gray-300 rounded text-sm"
                              autoFocus
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  handlePriceSave(product.id)
                                } else if (e.key === 'Escape') {
                                  handlePriceCancel()
                                }
                              }}
                            />
                            <button
                              onClick={() => handlePriceSave(product.id)}
                              className="px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
                              title="Запази"
                            >
                              ✓
                            </button>
                            <button
                              onClick={handlePriceCancel}
                              className="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500"
                              title="Отказ"
                            >
                              ×
                            </button>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2">
                            <span>€{product.price ? product.price.toFixed(2) : '0.00'}</span>
                            <button
                              onClick={() => handlePriceEdit(product.id, product.price)}
                              className="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition"
                              title="Редактирай цена"
                            >
                              ✎
                            </button>
                          </div>
                        )}
                      </td>
                      <td className="py-2 px-3 text-sm text-medium-grey">{product.category}</td>
                      <td className="py-2 px-3 text-sm text-medium-grey">{product.images.length}</td>
                      <td className="py-2 px-3 text-sm text-medium-grey">
                        {product.colors.map(c => c.name).join(', ')}
                      </td>
                      <td className="py-2 px-3 text-sm">
                        <button
                          onClick={() => handleDeleteProduct(product.id, product.name)}
                          className="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition text-xs font-medium"
                          title="Изтрий продукт"
                        >
                          Изтрий
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {products.length > 10 && (
                <p className="text-sm text-medium-grey mt-2">
                  Показване на първите 10 от {products.length} продукта
                </p>
              )}
            </div>
          </div>
        )}

        {/* Image Upload Section */}
        {products.length > 0 && (
          <div className="bg-white rounded-lg p-6 mt-6">
            <h2 className="text-lg font-semibold text-dark-grey mb-4">Качване на изображения</h2>
            <p className="text-sm text-medium-grey mb-4">
              Изберете продукт и качете изображения с произволни имена. Те ще бъдат автоматично именувани като product-{'{id}'}-{'{index}'}.jpg
            </p>
            
            {uploadStatus && (
              <div className={`p-3 rounded-lg mb-4 ${
                uploadStatus.includes('Грешка') 
                  ? 'bg-red-50 text-red-700' 
                  : 'bg-green-50 text-green-700'
              }`}>
                {uploadStatus}
              </div>
            )}

            {/* Quick Upload Section */}
            <div className="border border-gray-200 rounded-lg p-4 mb-6 bg-gray-50">
              <h3 className="font-medium text-dark-grey mb-4">Бързо качване (произволни имена)</h3>
              <div className="flex gap-4 items-end">
                <div className="flex-1">
                  <label className="block text-sm font-medium text-dark-grey mb-2">
                    Изберете продукт *
                  </label>
                  <select
                    value={selectedProductId || ''}
                    onChange={(e) => setSelectedProductId(e.target.value ? parseInt(e.target.value) : null)}
                    className="w-full px-4 py-2 border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-dark-grey focus:border-transparent"
                  >
                    <option value="">-- Изберете продукт --</option>
                    {products.map((product) => (
                      <option key={product.id} value={product.id}>
                        #{product.id} - {product.name} ({product.images.length} изображения)
                      </option>
                    ))}
                  </select>
                </div>
                <div className="flex-1">
                  <label className="block text-sm font-medium text-dark-grey mb-2">
                    Изберете изображения *
                  </label>
                  <label className="cursor-pointer block">
                    <input
                      type="file"
                      accept="image/*"
                      multiple
                      onChange={(e) => {
                        if (selectedProductId) {
                          handleImageUpload(e, selectedProductId)
                        } else {
                          setUploadStatus('Грешка: Моля, изберете продукт първо!')
                        }
                      }}
                      disabled={uploadingImages || !selectedProductId}
                      className="hidden"
                    />
                    <span className={`inline-block px-4 py-2 bg-light-pink text-dark-grey font-semibold rounded-lg transition text-sm ${
                      uploadingImages || !selectedProductId 
                        ? 'opacity-50 cursor-not-allowed' 
                        : 'hover:bg-opacity-80 cursor-pointer'
                    }`}>
                      {uploadingImages ? 'Качване...' : 'Качи изображения'}
                    </span>
                  </label>
                </div>
              </div>
              {selectedProductId && (
                <p className="text-xs text-medium-grey mt-2">
                  Изображенията ще бъдат автоматично именувани като: product-{selectedProductId}-1.jpg, product-{selectedProductId}-2.jpg, и т.н.
                </p>
              )}
            </div>

            {/* Product List with Current Images */}
            <div className="space-y-4">
              <h3 className="font-medium text-dark-grey mb-3">Всички продукти</h3>
              {products.map((product) => (
                <div key={product.id} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex-1">
                      <h3 className="font-medium text-dark-grey">
                        Продукт #{product.id}: {editingName === product.id ? (
                          <div className="inline-flex items-center gap-2 ml-2">
                            <input
                              type="text"
                              value={nameInputValue}
                              onChange={(e) => setNameInputValue(e.target.value)}
                              className="px-2 py-1 border border-gray-300 rounded text-sm"
                              autoFocus
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  handleNameSave(product.id)
                                } else if (e.key === 'Escape') {
                                  handleNameCancel()
                                }
                              }}
                            />
                            <button
                              onClick={() => handleNameSave(product.id)}
                              className="px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
                              title="Запази"
                            >
                              ✓
                            </button>
                            <button
                              onClick={handleNameCancel}
                              className="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500"
                              title="Отказ"
                            >
                              ×
                            </button>
                          </div>
                        ) : (
                          <>
                            <span>{product.name}</span>
                            <button
                              onClick={() => handleNameEdit(product.id, product.name)}
                              className="ml-2 px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition"
                              title="Редактирай име"
                            >
                              ✎
                            </button>
                          </>
                        )}
                      </h3>
                      <div className="flex items-center gap-2 mt-1">
                        <p className="text-sm text-medium-grey">
                          Цена: {editingPrice === product.id ? (
                            <div className="inline-flex items-center gap-2 ml-2">
                              <input
                                type="number"
                                step="0.01"
                                min="0"
                                value={priceInputValue}
                                onChange={(e) => setPriceInputValue(e.target.value)}
                                className="w-20 px-2 py-1 border border-gray-300 rounded text-sm"
                                autoFocus
                                onKeyDown={(e) => {
                                  if (e.key === 'Enter') {
                                    handlePriceSave(product.id)
                                  } else if (e.key === 'Escape') {
                                    handlePriceCancel()
                                  }
                                }}
                              />
                              <button
                                onClick={() => handlePriceSave(product.id)}
                                className="px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
                                title="Запази"
                              >
                                ✓
                              </button>
                              <button
                                onClick={handlePriceCancel}
                                className="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500"
                                title="Отказ"
                              >
                                ×
                              </button>
                            </div>
                          ) : (
                            <>
                              <span className="font-semibold text-dark-grey">€{product.price ? product.price.toFixed(2) : '0.00'}</span>
                              <button
                                onClick={() => handlePriceEdit(product.id, product.price)}
                                className="ml-2 px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition"
                                title="Редактирай цена"
                              >
                                ✎ Редактирай цена
                              </button>
                            </>
                          )}
                        </p>
                      </div>
                      <p className="text-sm text-medium-grey mt-1">
                        Текущи изображения: {product.images.length}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleDeleteProduct(product.id, product.name)}
                        className="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition text-sm font-medium"
                        title="Изтрий продукт"
                      >
                        Изтрий продукт
                      </button>
                      <label className="cursor-pointer">
                      <input
                        type="file"
                        accept="image/*"
                        multiple
                        onChange={(e) => handleImageUpload(e, product.id)}
                        disabled={uploadingImages}
                        className="hidden"
                      />
                      <span className={`px-4 py-2 bg-light-pink text-dark-grey font-semibold rounded-lg transition text-sm ${
                        uploadingImages ? 'opacity-50 cursor-not-allowed' : 'hover:bg-opacity-80 cursor-pointer'
                      }`}>
                        {uploadingImages ? 'Качване...' : 'Качи изображения'}
                      </span>
                    </label>
                    </div>
                  </div>
                  {product.images.length > 0 && (
                    <div className="flex gap-2 mt-3 flex-wrap">
                      {product.images.map((img, idx) => (
                        <div key={idx} className="relative group">
                          <div className="w-16 h-16 rounded overflow-hidden bg-gray-100 border-2 border-transparent group-hover:border-red-300 transition">
                            <img 
                              src={`/images/products/${img}`} 
                              alt={`${product.name} ${idx + 1}`}
                              className="w-full h-full object-cover"
                              onError={(e) => {
                                const target = e.currentTarget as HTMLImageElement
                                target.style.display = 'none'
                                const parent = target.parentElement
                                if (parent) {
                                  parent.innerHTML = '<div class="w-full h-full flex items-center justify-center text-xs text-red-500">Грешка</div>'
                                }
                              }}
                            />
                          </div>
                          <button
                            onClick={() => handleDeleteImage(product.id, img)}
                            className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-sm hover:bg-red-600 shadow-lg"
                            title={`Изтрий ${img}`}
                            type="button"
                          >
                            ×
                          </button>
                          <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-70 text-white text-xs p-1 truncate opacity-0 group-hover:opacity-100 transition-opacity rounded-b">
                            {img}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="bg-white rounded-lg p-6 mt-6">
          <h2 className="text-lg font-semibold text-dark-grey mb-4">Инструкции</h2>
          <ol className="list-decimal list-inside space-y-2 text-sm text-medium-grey">
            <li>Подгответе Excel файл с колони: Product Name, Product URL, Product Image, Price (EUR), Product Color, Product Size, Product Type</li>
            <li>Качете Excel файла чрез формата по-горе (без изображения)</li>
            <li>Прегледайте парсираните продукти</li>
            <li>Качете изображения за всеки продукт в секцията "Качване на изображения"</li>
            <li>Изтеглете или копирайте генерирания JSON файл</li>
            <li>Заменете съдържанието на data/products.json с новия JSON</li>
            <li>Копирайте изображенията в public/images/products/</li>
            <li>Продуктите ще се появят автоматично в магазина</li>
          </ol>
        </div>
      </div>
    </div>
  )
}

