"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Search, LayoutGrid, X } from "lucide-react";

type Categoria = { id: string; nombre: string; icono: string | null };

export default function CursosFilterClient({
  categorias,
  currentQuery,
  currentCategoria,
}: {
  categorias: Categoria[];
  currentQuery: string;
  currentCategoria: string;
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [query, setQuery] = useState(currentQuery);
  const [catOpen, setCatOpen] = useState(false);

  const buildUrl = (q: string, cat: string) => {
    const params = new URLSearchParams();
    if (q)   params.set("query", q);
    if (cat) params.set("categoria", cat);
    return `/cursos${params.toString() ? "?" + params.toString() : ""}`;
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    startTransition(() => router.push(buildUrl(query, currentCategoria)));
  };

  const handleCategoria = (nombre: string) => {
    const next = currentCategoria === nombre ? "" : nombre;
    setCatOpen(false);
    startTransition(() => router.push(buildUrl(query, next)));
  };

  const handleClear = () => {
    setQuery("");
    startTransition(() => router.push("/cursos"));
  };

  return (
    <div className="mb-10">
      {/* Barra principal */}
      <div className="flex flex-col md:flex-row gap-3 mb-5">
        {/* Selector de Categorías */}
        <div className="relative">
          <button
            onClick={() => setCatOpen(v => !v)}
            className={`flex items-center gap-2 px-5 py-3 rounded-xl border font-semibold text-sm transition-all shadow-sm ${
              currentCategoria
                ? "bg-[#1e2a47] text-white border-[#1e2a47]"
                : "bg-white text-gray-700 border-gray-200 hover:border-gray-300"
            }`}
          >
            <LayoutGrid className="w-4 h-4" />
            {currentCategoria || "Categorías"}
            {currentCategoria && (
              <X className="w-3.5 h-3.5 ml-1 opacity-70" />
            )}
          </button>

          {catOpen && (
            <div className="absolute z-30 top-full left-0 mt-2 w-72 bg-white border border-gray-100 rounded-xl shadow-2xl overflow-hidden">
              <div className="py-1 max-h-80 overflow-y-auto">
                <button
                  onClick={() => handleCategoria("")}
                  className="w-full text-left px-4 py-2.5 text-sm hover:bg-gray-50 font-semibold text-gray-500 border-b border-gray-50"
                >
                  🌐 Todas las categorías
                </button>
                {categorias.map(cat => (
                  <button
                    key={cat.id}
                    onClick={() => handleCategoria(cat.nombre)}
                    className={`w-full text-left px-4 py-2.5 text-sm hover:bg-blue-50 transition-colors flex items-center gap-2 ${
                      currentCategoria === cat.nombre ? "bg-blue-50 text-blue-700 font-bold" : "text-gray-700"
                    }`}
                  >
                    <span className="text-base">{cat.icono}</span>
                    {cat.nombre}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Buscador */}
        <form onSubmit={handleSearch} className="flex-1 flex items-center gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Buscar por nombre de curso, instructor o sede..."
              className="w-full pl-11 pr-4 py-3 rounded-xl border border-gray-200 bg-white text-sm focus:ring-2 focus:ring-[#0066ff] outline-none shadow-sm transition-all"
            />
            {query && (
              <button
                type="button"
                onClick={() => setQuery("")}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
          <button
            type="submit"
            className="bg-[#0066ff] hover:bg-blue-700 text-white font-bold px-6 py-3 rounded-xl text-sm transition-colors shadow-sm"
          >
            Buscar
          </button>
          {(query || currentCategoria) && (
            <button
              type="button"
              onClick={handleClear}
              className="text-sm text-gray-500 hover:text-red-500 font-semibold px-3 py-3 rounded-xl hover:bg-red-50 transition-colors"
            >
              Limpiar
            </button>
          )}
        </form>
      </div>

      {/* Chips de categorías populares */}
      <div className="flex flex-wrap gap-2">
        {categorias.filter(c => c.icono).slice(0, 8).map(cat => (
          <button
            key={cat.id}
            onClick={() => handleCategoria(cat.nombre)}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold border transition-all ${
              currentCategoria === cat.nombre
                ? "bg-[#1e2a47] text-white border-[#1e2a47]"
                : "bg-white text-gray-600 border-gray-200 hover:border-blue-300 hover:text-blue-600"
            }`}
          >
            <span>{cat.icono}</span> {cat.nombre}
          </button>
        ))}
      </div>
    </div>
  );
}
