"use client";
import { useState, useEffect, useMemo, useCallback } from "react";
import { useAuth } from "./useAuth.js";
import { extractUserPlanData } from "../lib/user-data-utils.js";
import { getEnabledEntities } from "../lib/entities/registry.client.js";
function useEntitySearch() {
  const [query, setQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [results, setResults] = useState([]);
  const { user } = useAuth();
  const userPlanData = useMemo(() => {
    return extractUserPlanData(user);
  }, [user]);
  const [availableEntities, setAvailableEntities] = useState([]);
  useEffect(() => {
    if (!user || !user.role) {
      setAvailableEntities([]);
      return;
    }
    try {
      const entities = getEnabledEntities().filter(
        (entity) => {
          var _a, _b;
          return entity.enabled && ((_b = (_a = entity.ui) == null ? void 0 : _a.features) == null ? void 0 : _b.searchable);
        }
      );
      setAvailableEntities(entities);
    } catch (error) {
      console.error("Error getting user entities for search:", error);
      setAvailableEntities([]);
    }
  }, [user]);
  const systemResults = useMemo(() => {
    const systemPages = [
      {
        id: "dashboard",
        title: "Dashboard",
        description: "Panel principal con estad\xEDsticas y acciones r\xE1pidas",
        url: "/dashboard",
        category: "Navigation"
      },
      {
        id: "profile",
        title: "Configuraci\xF3n de Perfil",
        description: "Actualizar informaci\xF3n personal y preferencias",
        url: "/dashboard/settings/profile",
        category: "Settings"
      },
      {
        id: "security",
        title: "Configuraci\xF3n de Seguridad",
        description: "Autenticaci\xF3n de dos factores y sesiones activas",
        url: "/dashboard/settings/security",
        category: "Settings"
      },
      {
        id: "notifications",
        title: "Configuraci\xF3n de Notificaciones",
        description: "Preferencias de emails y notificaciones push",
        url: "/dashboard/settings/notifications",
        category: "Settings"
      },
      {
        id: "billing",
        title: "Facturaci\xF3n",
        description: "Planes, m\xE9todos de pago y historial de facturaci\xF3n",
        url: "/dashboard/settings/billing",
        category: "Settings"
      }
    ];
    return systemPages.map((page) => ({
      ...page,
      entityType: "system",
      type: "system",
      priority: "low"
    }));
  }, []);
  const entityResults = useMemo(() => {
    if (!availableEntities.length) return [];
    return availableEntities.map((entity) => ({
      id: `entity-${entity.slug}`,
      title: entity.names.singular,
      description: `Gestionar ${entity.names.plural.toLowerCase()}`,
      entityType: entity.slug,
      type: "entity",
      url: `/dashboard/${entity.slug}`,
      category: "Entities",
      priority: "medium",
      icon: entity.icon.name || "FileText",
      limitInfo: {
        current: 0,
        // This would be fetched from actual usage data
        max: userPlanData.plan === "premium" ? "unlimited" : userPlanData.plan === "starter" ? 100 : 10,
        canCreate: true
        // This would be calculated based on current usage vs limits
      }
    }));
  }, [availableEntities, userPlanData.plan]);
  const allSearchableItems = useMemo(() => {
    return [...entityResults, ...systemResults];
  }, [entityResults, systemResults]);
  const getRelevanceScore = useCallback((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 (item.entityType.toLowerCase() === query2) score += 80;
    if (item.entityType.toLowerCase().includes(query2)) score += 30;
    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;
    if (item.type === "entity") score += 5;
    return score;
  }, []);
  const performSearch = useCallback((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);
      const entityTypeMatch = item.entityType.toLowerCase().includes(lowercaseQuery);
      return titleMatch || descriptionMatch || categoryMatch || entityTypeMatch;
    }).sort((a, b) => {
      const aScore = getRelevanceScore(a, lowercaseQuery);
      const bScore = getRelevanceScore(b, lowercaseQuery);
      if (aScore !== bScore) {
        return bScore - aScore;
      }
      if (a.type === "entity" && b.type === "system") return -1;
      if (a.type === "system" && b.type === "entity") return 1;
      const priorityOrder = { high: 3, medium: 2, low: 1 };
      const aPriority = priorityOrder[a.priority || "low"];
      const bPriority = priorityOrder[b.priority || "low"];
      if (aPriority !== bPriority) {
        return bPriority - aPriority;
      }
      return a.title.localeCompare(b.title);
    }).slice(0, 12);
  }, [allSearchableItems, getRelevanceScore]);
  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(() => {
      try {
        const searchResults = performSearch(trimmedQuery);
        setResults(searchResults);
      } catch (error) {
        console.error("Error performing search:", error);
        setResults([]);
      } finally {
        setIsSearching(false);
      }
    }, 150);
    return () => clearTimeout(searchTimeout);
  }, [query, user, performSearch]);
  const clearSearch = useCallback(() => {
    setQuery("");
    setResults([]);
    setIsSearching(false);
  }, []);
  return {
    query,
    setQuery,
    results,
    isSearching,
    clearSearch,
    hasResults: results.length > 0,
    isEmpty: query.trim().length === 0,
    availableEntities
  };
}
export {
  useEntitySearch
};
