'use client'

import { useState, useEffect, useRef } from 'react'
import Link from 'next/link'
import api from '@/lib/api'
import BarcodeLabel from '@/components/BarcodeLabel'
import { PrinterIcon, DownloadIcon } from '@/components/Icons'

interface Item {
  id: number
  sku: string
  name: string
  category: string | null
  unit: string
  active: boolean
}

export default function EtiquetasPage() {
  const [items, setItems] = useState<Item[]>([])
  const [categories, setCategories] = useState<string[]>([])
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [loading, setLoading] = useState(false)
  const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set())
  const printRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    loadCategories()
  }, [])

  useEffect(() => {
    loadItems()
  }, [selectedCategory])

  const loadCategories = async () => {
    try {
      const response = await api.get('/items/categories/list')
      setCategories(response.data)
    } catch (error) {
      console.error('Error loading categories:', error)
    }
  }

  const loadItems = async () => {
    setLoading(true)
    try {
      const params: any = { activeOnly: 'true' }
      if (selectedCategory) {
        params.category = selectedCategory
      }
      const response = await api.get('/items', { params })
      setItems(response.data)
      // Seleccionar todos por defecto
      setSelectedItems(new Set(response.data.map((item: Item) => item.id)))
    } catch (error) {
      console.error('Error loading items:', error)
    } finally {
      setLoading(false)
    }
  }

  const toggleItem = (itemId: number) => {
    const newSelected = new Set(selectedItems)
    if (newSelected.has(itemId)) {
      newSelected.delete(itemId)
    } else {
      newSelected.add(itemId)
    }
    setSelectedItems(newSelected)
  }

  const selectAll = () => {
    setSelectedItems(new Set(items.map((item) => item.id)))
  }

  const deselectAll = () => {
    setSelectedItems(new Set())
  }

  const handlePrint = () => {
    if (selectedItems.size === 0) {
      alert('Por favor, seleccione al menos un artículo para imprimir')
      return
    }

    const printWindow = window.open('', '_blank')
    if (!printWindow) return

    const selectedItemsData = items.filter((item) => selectedItems.has(item.id))

    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Etiquetas de Códigos de Barras</title>
          <style>
            @media print {
              @page {
                size: letter;
                margin: 0.5in;
              }
              body {
                margin: 0;
                padding: 0;
              }
            }
            body {
              font-family: Arial, sans-serif;
              display: flex;
              flex-wrap: wrap;
              gap: 10px;
              padding: 10px;
            }
            .label {
              border: 1px solid #ccc;
              padding: 12px;
              background: white;
              width: 3.5in;
              min-height: 2in;
              page-break-inside: avoid;
            }
            .label-header {
              text-align: center;
              font-size: 10px;
              font-weight: bold;
              color: #333;
              margin-bottom: 4px;
            }
            .label-name {
              text-align: center;
              font-size: 13px;
              font-weight: 600;
              color: #000;
              margin-bottom: 8px;
              min-height: 2.5em;
            }
            .label-category {
              text-align: center;
              font-size: 11px;
              color: #666;
              margin-bottom: 4px;
            }
            .barcode-container {
              text-align: center;
              margin: 8px 0;
            }
            .label-sku {
              text-align: center;
              font-size: 11px;
              font-family: monospace;
              font-weight: 600;
              color: #333;
              margin-top: 4px;
            }
            .label-unit {
              text-align: center;
              font-size: 11px;
              color: #666;
              margin-top: 4px;
            }
            svg {
              max-width: 100%;
            }
          </style>
          <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
        </head>
        <body>
          ${selectedItemsData
            .map(
              (item) => `
            <div class="label">
              <div class="label-header">SISTEMA DE INVENTARIO</div>
              <div class="label-name">${item.name}</div>
              ${item.category ? `<div class="label-category">Categoría: ${item.category}</div>` : ''}
              <div class="barcode-container">
                <svg id="barcode-${item.id}"></svg>
              </div>
              <div class="label-sku">SKU: ${item.sku}</div>
              ${item.unit ? `<div class="label-unit">Unidad: ${item.unit}</div>` : ''}
            </div>
            <script>
              (function() {
                try {
                  JsBarcode('#barcode-${item.id}', '${item.sku}', {
                    format: 'CODE128',
                    width: 2,
                    height: 60,
                    displayValue: true,
                    fontSize: 14,
                    margin: 10,
                  });
                } catch(e) {
                  console.error('Error generating barcode:', e);
                }
              })();
            </script>
          `,
            )
            .join('')}
        </body>
      </html>
    `)

    printWindow.document.close()

    // Wait for barcodes to render, then print
    setTimeout(() => {
      printWindow.print()
    }, 500)
  }

  const filteredItems = items.filter((item) => selectedItems.has(item.id))

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Etiquetas de Códigos de Barras</h1>
          <p className="text-sm text-gray-600 mt-1">Genere e imprima etiquetas de códigos de barras para artículos</p>
        </div>
        <Link
          href="/maestros/articulos"
          className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
        >
          ← Volver
        </Link>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-2">
              Filtrar por Categoría
            </label>
            <select
              id="category"
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="">Todas las categorías</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat}
                </option>
              ))}
            </select>
          </div>
          <div className="flex items-end gap-2">
            <button
              onClick={selectAll}
              className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 transition"
            >
              Seleccionar Todos
            </button>
            <button
              onClick={deselectAll}
              className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 transition"
            >
              Deseleccionar Todos
            </button>
          </div>
        </div>
      </div>

      {/* Items List */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900">
            Artículos {selectedCategory && `- ${selectedCategory}`}
          </h2>
          <div className="text-sm text-gray-600">
            {selectedItems.size} de {items.length} seleccionados
          </div>
        </div>

        {loading ? (
          <div className="text-center py-8 text-gray-500">Cargando artículos...</div>
        ) : items.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            No hay artículos {selectedCategory ? `en la categoría "${selectedCategory}"` : 'disponibles'}
          </div>
        ) : (
          <div className="space-y-2 max-h-96 overflow-y-auto">
            {items.map((item) => (
              <label
                key={item.id}
                className="flex items-center gap-3 p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
              >
                <input
                  type="checkbox"
                  checked={selectedItems.has(item.id)}
                  onChange={() => toggleItem(item.id)}
                  className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900">{item.name}</div>
                  <div className="text-sm text-gray-600">SKU: {item.sku}</div>
                  {item.category && <div className="text-xs text-gray-500">Categoría: {item.category}</div>}
                </div>
              </label>
            ))}
          </div>
        )}
      </div>

      {/* Preview and Print */}
      {filteredItems.length > 0 && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">
              Vista Previa ({filteredItems.length} {filteredItems.length === 1 ? 'etiqueta' : 'etiquetas'})
            </h2>
            <button
              onClick={handlePrint}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-semibold hover:bg-blue-700 transition shadow-sm hover:shadow"
            >
              <PrinterIcon className="w-4 h-4" />
              Imprimir Etiquetas
            </button>
          </div>

          <div ref={printRef} className="flex flex-wrap gap-4 p-4 bg-gray-50 rounded-lg">
            {filteredItems.map((item) => (
              <BarcodeLabel
                key={item.id}
                sku={item.sku}
                name={item.name}
                category={item.category || undefined}
                unit={item.unit}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
