"use client";
import { useState, useEffect, useMemo } from "react";
import { useAuth } from "./useAuth";
import { ENTITY_REGISTRY } from "../lib/entities/queries";
import { SEARCH_TYPE_PRIORITIES } from "@nextsparkjs/registries/entity-types";
const getSearchableEntities = () => {
  return Object.values(ENTITY_REGISTRY).filter((entry) => {
    var _a, _b;
    const config = entry.config;
    return ((_b = (_a = config.ui) == null ? void 0 : _a.features) == null ? void 0 : _b.searchable) === true;
  });
};
const generateEntitySearchResults = () => {
  const searchableEntities = getSearchableEntities();
  return searchableEntities.map((entry) => {
    var _a, _b, _c;
    const config = entry.config;
    const entityName = config.slug || entry.name;
    const displayName = ((_a = config.names) == null ? void 0 : _a.singular) || entityName;
    return {
      id: `entity-${entry.name}`,
      title: displayName,
      description: `Gesti\xF3n de ${((_c = (_b = config.names) == null ? void 0 : _b.plural) == null ? void 0 : _c.toLowerCase()) || displayName.toLowerCase()}`,
      type: entry.name,
      // Map to specific entity types
      url: `/dashboard/${config.slug || entry.name}`,
      category: "Entidades",
      entityType: entry.name,
      priority: "medium"
    };
  });
};
const getSearchableFields = (entityConfig) => {
  if (!entityConfig.fields) return [];
  return entityConfig.fields.filter((field) => {
    var _a;
    return ((_a = field.api) == null ? void 0 : _a.searchable) === true;
  }).map((field) => field.name);
};
const SYSTEM_PAGES = [
  {
    title: "Dashboard",
    description: "Panel principal con estad\xEDsticas y acciones r\xE1pidas",
    type: "page",
    url: "/dashboard"
  },
  {
    title: "Gesti\xF3n de Tareas",
    description: "Crear, editar y organizar tus tareas",
    type: "page",
    url: "/dashboard/tasks"
  },
  {
    title: "Configuraci\xF3n de Perfil",
    description: "Actualizar informaci\xF3n personal y preferencias",
    type: "setting",
    url: "/dashboard/settings/profile"
  },
  {
    title: "Configuraci\xF3n de Seguridad",
    description: "Autenticaci\xF3n de dos factores y sesiones activas",
    type: "setting",
    url: "/dashboard/settings/security"
  },
  {
    title: "Configuraci\xF3n de Notificaciones",
    description: "Preferencias de emails y notificaciones push",
    type: "setting",
    url: "/dashboard/settings/notifications"
  },
  {
    title: "Configuraci\xF3n de Contrase\xF1a",
    description: "Cambiar contrase\xF1a y opciones de seguridad",
    type: "setting",
    url: "/dashboard/settings/password"
  },
  {
    title: "Facturaci\xF3n",
    description: "Planes, m\xE9todos de pago y historial de facturaci\xF3n",
    type: "setting",
    url: "/dashboard/settings/billing"
  }
];
function useSearch() {
  const [query, setQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [results, setResults] = useState([]);
  const { user } = useAuth();
  const entityResults = useMemo(() => {
    return generateEntitySearchResults();
  }, []);
  const allSearchableItems = useMemo(() => {
    const systemResults = SYSTEM_PAGES.map((page, index) => ({
      id: `page-${index}`,
      ...page
    }));
    return [...entityResults, ...systemResults];
  }, [entityResults]);
  const performSearch = useMemo(() => {
    return (searchQuery) => {
      if (!searchQuery.trim()) return [];
      const lowercaseQuery = searchQuery.toLowerCase();
      return allSearchableItems.filter((item) => {
        var _a, _b;
        const titleMatch = item.title.toLowerCase().includes(lowercaseQuery);
        const descriptionMatch = (_a = item.description) == null ? void 0 : _a.toLowerCase().includes(lowercaseQuery);
        const categoryMatch = (_b = item.category) == null ? void 0 : _b.toLowerCase().includes(lowercaseQuery);
        return titleMatch || descriptionMatch || categoryMatch;
      }).sort((a, b) => {
        const aScore = getRelevanceScore(a, lowercaseQuery);
        const bScore = getRelevanceScore(b, lowercaseQuery);
        if (aScore !== bScore) {
          return bScore - aScore;
        }
        const aTypeScore = SEARCH_TYPE_PRIORITIES[a.type] || 0;
        const bTypeScore = SEARCH_TYPE_PRIORITIES[b.type] || 0;
        if (aTypeScore !== bTypeScore) {
          return bTypeScore - aTypeScore;
        }
        if (a.priority && b.priority) {
          const priorityOrder = { high: 3, medium: 2, low: 1 };
          return (priorityOrder[b.priority] || 0) - (priorityOrder[a.priority] || 0);
        }
        return a.title.localeCompare(b.title);
      }).slice(0, 8);
    };
  }, [allSearchableItems]);
  const getRelevanceScore = (item, query2) => {
    var _a, _b;
    let score = 0;
    if (item.title.toLowerCase() === query2) score += 100;
    if (item.title.toLowerCase().startsWith(query2)) score += 50;
    if (item.title.toLowerCase().includes(query2)) score += 25;
    if ((_a = item.description) == null ? void 0 : _a.toLowerCase().includes(query2)) score += 10;
    if ((_b = item.category) == null ? void 0 : _b.toLowerCase().includes(query2)) score += 5;
    return score;
  };
  useEffect(() => {
    if (!user) {
      setResults([]);
      return;
    }
    const trimmedQuery = query.trim();
    if (trimmedQuery.length === 0) {
      setResults([]);
      setIsSearching(false);
      return;
    }
    if (trimmedQuery.length < 2) {
      setResults([]);
      setIsSearching(false);
      return;
    }
    setIsSearching(true);
    const searchTimeout = setTimeout(() => {
      const searchResults = performSearch(trimmedQuery);
      setResults(searchResults);
      setIsSearching(false);
    }, 150);
    return () => clearTimeout(searchTimeout);
  }, [query, user, performSearch]);
  const clearSearch = () => {
    setQuery("");
    setResults([]);
    setIsSearching(false);
  };
  return {
    query,
    setQuery,
    results,
    isSearching,
    clearSearch,
    hasResults: results.length > 0,
    isEmpty: query.trim().length === 0
  };
}
export {
  useSearch
};
