'use client';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import type { Product } from '@/types';
import { productsApi } from '@/lib/api-client';

const PAGE_SIZE = 20;

function formatPrice(cents?: number) {
  if (cents == null) return '—';
  return `€${(cents / 100).toFixed(2)}`;
}

/** Renders HTML safely: strips dangerous tags while preserving safe formatting. */
function renderHtml(html: string): string {
  if (!html) return '';
  return html
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
    .replace(/\son\w+="[^"]*"/gi, '')
    .replace(/\son\w+='[^']*'/gi, '')
    .replace(/javascript:/gi, '')
    .replace(/<iframe/gi, '&lt;iframe')
    .replace(/<object/gi, '&lt;object')
    .replace(/<embed/gi, '&lt;embed');
}

function StateBadge({ state }: { state: string }) {
  const map: Record<string, { label: string; cls: string }> = {
    active: { label: 'Activo', cls: 'bg-green-100 text-green-800' },
    archived: { label: 'Archivado', cls: 'bg-gray-100 text-gray-600' },
    draft: { label: 'Borrador', cls: 'bg-amber-100 text-amber-800' },
  };
  const { label, cls } = map[state] ?? { label: state, cls: 'bg-gray-100 text-gray-600' };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${cls}`}>
      {label}
    </span>
  );
}

export default function ProductsPage() {
  const router = useRouter();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [page, setPage] = useState(0);
  const [total, setTotal] = useState(0);
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'archived'>('all');

  // Debounce search
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search), 400);
    return () => clearTimeout(t);
  }, [search]);

  // Reset page on search change
  useEffect(() => {
    setPage(0);
  }, [debouncedSearch]);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const data = await productsApi.list({
        limit: PAGE_SIZE,
        offset: paginationEnabled ? page * PAGE_SIZE : 0,
        q: debouncedSearch || undefined,
      });
      setProducts(data.items ?? []);
      setTotal(data.items?.length ?? 0);
      if (!paginationEnabled) setPage(0);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar');
    } finally {
      setLoading(false);
    }
  }, [page, debouncedSearch]);

  useEffect(() => { load(); }, [load]);

  const paginationEnabled = statusFilter === 'all' && !debouncedSearch;
  const totalPages = paginationEnabled ? (Math.ceil(total / PAGE_SIZE) || 1) : 1;

  const filteredProducts = statusFilter === 'all'
    ? products
    : products.filter(p => p.state === statusFilter);

  const filteredTotal = filteredProducts.length;

  return (
    <div className="p-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Productos</h1>
          <p className="text-sm text-gray-500 mt-0.5">
            {filteredTotal} producto{filteredTotal !== 1 ? 's' : ''}
            {statusFilter !== 'all' ? ` (${statusFilter === 'active' ? 'activos' : 'archivados'})` : ''}
          </p>
        </div>
        <Link
          href="/products/new"
          className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl transition-colors"
        >
          + Crear producto
        </Link>
      </div>

      {/* Search */}
      <div className="mb-6">
        <div className="mb-4 flex gap-2">
          {(['all', 'active', 'archived'] as const).map(f => (
            <button
              key={f}
              onClick={() => setStatusFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                statusFilter === f
                  ? 'bg-[#2D6A4F] text-white'
                  : 'bg-white border border-gray-300 text-gray-600 hover:bg-gray-50'
              }`}
            >
              {f === 'all' ? 'Todos' : f === 'active' ? 'Activos' : 'Archivados'}
            </button>
          ))}
        </div>

        <div className="relative max-w-md">
          <input
            type="search"
            id="admin-products-search"
            name="q"
            placeholder="Buscar por nombre..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none"
          />
          <svg
            className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <circle cx="11" cy="11" r="8" />
            <path d="M21 21l-4.35-4.35" />
          </svg>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        {loading ? (
          <div className="text-center text-gray-400">
            <div className="inline-block animate-spin h-5 w-5 border-2 border-gray-300 border-t-[#2D6A4F] rounded-full" />
            <p className="mt-2 text-sm">Cargando...</p>
          </div>
        ) : error ? (
          <div className="text-center">
            <p className="text-red-600 text-sm mb-3">{error}</p>
            <button
              onClick={load}
              className="text-sm text-[#2D6A4F] hover:underline"
            >
              Reintentar
            </button>
          </div>
        ) : products.length === 0 ? (
          <div className="p-12 text-center">
            <p className="text-4xl mb-3">📦</p>
            <p className="text-gray-500 text-sm">
              {debouncedSearch ? 'No hay productos para esta búsqueda' : 'No hay productos'}
            </p>
          </div>
        ) : (
          <>
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">
                    Producto
                  </th>
                  <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">
                    Marca
                  </th>
                  <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">
                    Caducidad
                  </th>
                  <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">
                    Estado
                  </th>
                  <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">
                    Tienda
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {filteredProducts.map((p) => (
                  <tr
                    key={p.id}
                    className="hover:bg-gray-50 transition-colors cursor-pointer"
                    onClick={() => router.push(`/products/${p.id}`)}
                  >
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-3">
                        {p.images?.[0]?.url ? (
                          <div className="w-10 h-14 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0 overflow-hidden">
                            <img
                              src={p.images[0].url.replace('/uploads/', '/uploads/40/')}
                              alt={p.name}
                              className="max-w-full max-h-full w-auto h-auto object-contain"
                            />
                          </div>
                        ) : (
                          <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-lg flex-shrink-0">
                            🌿
                          </div>
                        )}
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-gray-900 truncate max-w-xs">
                            {p.name}
                          </p>
                          <p
                            className="text-xs text-gray-400 truncate max-w-xs"
                            dangerouslySetInnerHTML={{
                              __html: renderHtml(p.description ?? '').slice(0, 60) || p.slug,
                            }}
                          />
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-sm text-gray-600">{p.brand?.name ?? '—'}</p>
                    </td>
                    <td className="px-4 py-3">
                      {p.expirationDate ? (
                        (() => {
                          const today = new Date();
                          today.setHours(0, 0, 0, 0);
                          const exp = new Date(p.expirationDate);
                          const expired = exp < today;
                          return (
                            <span
                              className={`text-sm ${expired ? 'text-red-600 font-semibold' : 'text-gray-600'}`}
                              title={expired ? 'Producto caducado' : 'Caduca el'}
                            >
                              {expired ? '⚠ ' : ''}
                              {exp.toLocaleDateString('es-ES')}
                            </span>
                          );
                        })()
                      ) : (
                        <span className="text-sm text-gray-400">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <StateBadge state={p.state} />
                    </td>
                    <td className="px-4 py-3">
                      {p.state === 'active' ? (
                        <a
                          href={`http://192.168.18.93:3003/products/${p.slug}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          title="Ver en la tienda"
                          className="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-green-50 text-green-600 hover:bg-green-100 transition-colors"
                          onClick={e => e.stopPropagation()}
                        >
                          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                          </svg>
                        </a>
                      ) : (
                        <span className="w-8 block" />
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-gray-50">
                <p className="text-sm text-gray-500">
                  {paginationEnabled ? `Página ${page + 1} de ${totalPages}` : 'Mostrando resultados filtrados'}
                </p>
                {paginationEnabled && (
                  <div className="flex gap-2">
                    <button
                      onClick={() => setPage((p) => Math.max(0, p - 1))}
                      disabled={page === 0}
                      className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg disabled:opacity-40 hover:bg-white transition-colors"
                    >
                      ← Anterior
                    </button>
                    <button
                      onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
                      disabled={page >= totalPages - 1}
                      className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg disabled:opacity-40 hover:bg-white transition-colors"
                    >
                      Siguiente →
                    </button>
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
