"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import React, { useState, useMemo, useEffect, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent } from "../ui/card";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Badge } from "../ui/badge";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator
} from "../ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "../ui/popover";
import {
  Search,
  Filter,
  X,
  Loader2,
  ExternalLink,
  Calendar,
  User
} from "lucide-react";
import { useAuth } from "../../hooks/useAuth";
import { createTestId, createCyId } from "../../lib/test";
async function performSearch(query, accessibleEntities, filters = {}, maxResults = 50) {
  await new Promise((resolve) => setTimeout(resolve, 150));
  if (!query.trim()) return [];
  const results = [];
  const searchTerm = query.toLowerCase().trim();
  for (const entityConfig of accessibleEntities) {
    if (filters.entityName && filters.entityName !== entityConfig.slug) {
      continue;
    }
    const mockItems = generateMockSearchData(entityConfig, searchTerm);
    for (const item of mockItems) {
      if (results.length >= maxResults) break;
      const matches = findSearchMatches(item, entityConfig, searchTerm);
      if (matches.length > 0) {
        results.push({
          id: String(item.id),
          entityName: entityConfig.slug,
          entityConfig,
          title: String(item.title || item.name || `${entityConfig.names.singular} #${item.id}`),
          description: String(item.description || generateDescription(item, entityConfig)),
          matches,
          url: `/dashboard/${entityConfig.slug}/${item.id}`,
          metadata: {
            createdAt: item.createdAt ? String(item.createdAt) : void 0,
            updatedAt: item.updatedAt ? String(item.updatedAt) : void 0,
            createdBy: item.createdBy ? String(item.createdBy) : void 0
          },
          data: item
        });
      }
    }
  }
  return results.sort((a, b) => b.matches.length - a.matches.length);
}
function generateMockSearchData(entityConfig, searchTerm) {
  const items = [];
  for (let i = 1; i <= 5; i++) {
    const item = {
      id: `${entityConfig.slug}-${i}`,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1e3).toISOString(),
      updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1e3).toISOString(),
      createdBy: `user-${Math.floor(Math.random() * 10) + 1}`
    };
    entityConfig.fields.forEach((field) => {
      var _a, _b;
      switch (field.type) {
        case "text":
        case "textarea":
          item[field.name] = `${searchTerm} ${field.name} example ${i}`;
          break;
        case "email":
          item[field.name] = `${searchTerm}${i}@example.com`;
          break;
        case "boolean":
          item[field.name] = Math.random() > 0.5;
          break;
        case "number":
          item[field.name] = Math.floor(Math.random() * 1e3) + 1;
          break;
        case "select":
          item[field.name] = ((_b = (_a = field.options) == null ? void 0 : _a[0]) == null ? void 0 : _b.value) || "option1";
          break;
        default:
          item[field.name] = `${field.name} value ${i}`;
      }
    });
    items.push(item);
  }
  return items;
}
function findSearchMatches(item, entityConfig, searchTerm) {
  const matches = [];
  const searchWords = searchTerm.toLowerCase().split(" ").filter((w) => w.length > 0);
  entityConfig.fields.forEach((field) => {
    if (!field.api.searchable) return;
    const value = String(item[field.name] || "");
    const lowerValue = value.toLowerCase();
    const highlights = [];
    searchWords.forEach((word) => {
      let startIndex = 0;
      while (true) {
        const index = lowerValue.indexOf(word, startIndex);
        if (index === -1) break;
        highlights.push({
          start: index,
          end: index + word.length
        });
        startIndex = index + word.length;
      }
    });
    if (highlights.length > 0) {
      matches.push({
        field: field.name,
        fieldLabel: field.display.label,
        value,
        highlights: highlights.sort((a, b) => a.start - b.start)
      });
    }
  });
  return matches;
}
function generateDescription(item, entityConfig) {
  const descFields = ["description", "summary", "content", "notes"];
  for (const fieldName of descFields) {
    const field = entityConfig.fields.find((f) => f.name === fieldName);
    if (field && item[fieldName]) {
      const value = String(item[fieldName]);
      return value.length > 100 ? value.substring(0, 100) + "..." : value;
    }
  }
  return `${entityConfig.names.singular} created ${formatDate(item.createdAt)}`;
}
function formatDate(dateString) {
  try {
    return new Date(dateString).toLocaleDateString();
  } catch {
    return "recently";
  }
}
function highlightMatches(text, highlights) {
  if (highlights.length === 0) return text;
  const elements = [];
  let lastEnd = 0;
  highlights.forEach((highlight, index) => {
    if (highlight.start > lastEnd) {
      elements.push(text.slice(lastEnd, highlight.start));
    }
    elements.push(
      /* @__PURE__ */ jsx("mark", { className: "bg-yellow-200 font-medium rounded px-1", children: text.slice(highlight.start, highlight.end) }, index)
    );
    lastEnd = highlight.end;
  });
  if (lastEnd < text.length) {
    elements.push(text.slice(lastEnd));
  }
  return /* @__PURE__ */ jsx(Fragment, { children: elements });
}
function generateTestIds() {
  return {
    container: createTestId("search", "container"),
    input: createTestId("search", "input"),
    results: createTestId("search", "results"),
    result: (id) => createTestId("search", "result", id),
    filter: createTestId("search", "filter")
  };
}
function EntitySearch({
  entities,
  placeholder = "Search everything...",
  variant = "inline",
  onResultClick,
  onSearch,
  enableEntityFilter = true,
  maxResults = 20,
  className
}) {
  var _a;
  const { user } = useAuth();
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [results, setResults] = useState([]);
  const [filters, setFilters] = useState({});
  const [isOpen, setIsOpen] = useState(false);
  const searchTimeoutRef = useRef(null);
  const testIds = generateTestIds();
  const accessibleEntities = useMemo(() => {
    if (!user) return [];
    return entities.filter((entity) => {
      var _a2, _b;
      return (_b = (_a2 = entity.ui) == null ? void 0 : _a2.features) == null ? void 0 : _b.searchable;
    }).sort((a, b) => a.names.singular.localeCompare(b.names.singular));
  }, [user, entities]);
  const performSearchDebounced = useCallback(async (searchQuery) => {
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    if (!searchQuery.trim()) {
      setResults([]);
      setIsSearching(false);
      return;
    }
    setIsSearching(true);
    searchTimeoutRef.current = setTimeout(async () => {
      try {
        const searchResults = await performSearch(searchQuery, accessibleEntities, filters, maxResults);
        setResults(searchResults);
        onSearch == null ? void 0 : onSearch(searchQuery, filters.entityName);
      } catch (error) {
        console.error("Search failed:", error);
        setResults([]);
      } finally {
        setIsSearching(false);
      }
    }, 300);
  }, [accessibleEntities, filters, maxResults, onSearch]);
  const handleSearchChange = useCallback((value) => {
    setQuery(value);
    performSearchDebounced(value);
    if (variant === "dropdown") {
      setIsOpen(value.length > 0);
    }
  }, [performSearchDebounced, variant]);
  const handleResultClick = useCallback((result) => {
    if (onResultClick) {
      onResultClick(result);
    } else {
      router.push(result.url);
    }
    if (variant === "dropdown") {
      setIsOpen(false);
      setQuery("");
    }
  }, [onResultClick, router, variant]);
  const handleFilterChange = useCallback((newFilters) => {
    setFilters(newFilters);
    if (query.trim()) {
      performSearchDebounced(query);
    }
  }, [query, performSearchDebounced]);
  const handleClear = useCallback(() => {
    setQuery("");
    setResults([]);
    setFilters({});
    setIsOpen(false);
  }, []);
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);
  if (!user) return null;
  if (variant === "dropdown") {
    return /* @__PURE__ */ jsxs(Popover, { open: isOpen, onOpenChange: setIsOpen, children: [
      /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "outline",
          role: "combobox",
          "aria-expanded": isOpen,
          className: `justify-between ${className || ""}`,
          "data-testid": testIds.container,
          "data-cy": createCyId("search", "trigger"),
          children: [
            /* @__PURE__ */ jsx(Search, { className: "mr-2 h-4 w-4" }),
            query || placeholder
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(PopoverContent, { className: "w-[400px] p-0", align: "start", children: /* @__PURE__ */ jsxs(Command, { children: [
        /* @__PURE__ */ jsx(
          CommandInput,
          {
            placeholder,
            value: query,
            onValueChange: handleSearchChange,
            "data-testid": testIds.input
          }
        ),
        /* @__PURE__ */ jsxs(CommandList, { children: [
          isSearching && /* @__PURE__ */ jsxs(CommandItem, { disabled: true, children: [
            /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
            "Searching..."
          ] }),
          !isSearching && query && results.length === 0 && /* @__PURE__ */ jsx(CommandEmpty, { children: "No results found." }),
          results.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
            enableEntityFilter && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsxs(CommandGroup, { heading: "Filter by Type", children: [
                /* @__PURE__ */ jsx(CommandItem, { onSelect: () => handleFilterChange({}), children: "All Types" }),
                accessibleEntities.map((entity) => /* @__PURE__ */ jsxs(
                  CommandItem,
                  {
                    onSelect: () => handleFilterChange({ entityName: entity.slug }),
                    children: [
                      React.createElement(entity.icon, { className: "mr-2 h-4 w-4" }),
                      entity.names.plural
                    ]
                  },
                  entity.slug
                ))
              ] }),
              /* @__PURE__ */ jsx(CommandSeparator, {})
            ] }),
            /* @__PURE__ */ jsx(CommandGroup, { heading: "Results", children: results.map((result) => /* @__PURE__ */ jsx(
              CommandItem,
              {
                onSelect: () => handleResultClick(result),
                "data-testid": testIds.result(result.id),
                children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 w-full", children: [
                  React.createElement(result.entityConfig.icon, {
                    className: "h-4 w-4 text-muted-foreground flex-shrink-0"
                  }),
                  /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
                    /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: result.title }),
                    result.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground truncate", children: result.description })
                  ] }),
                  /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: result.entityConfig.names.singular })
                ] })
              },
              `${result.entityName}-${result.id}`
            )) })
          ] })
        ] })
      ] }) })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: `w-full space-y-4 ${className || ""}`, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "relative flex-1", children: [
        /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            placeholder,
            value: query,
            onChange: (e) => handleSearchChange(e.target.value),
            className: "pl-9 pr-9",
            "data-testid": testIds.input,
            "data-cy": createCyId("search", "input")
          }
        ),
        query && /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            onClick: handleClear,
            className: "absolute right-1 top-1 h-7 w-7 p-0",
            children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
          }
        )
      ] }),
      enableEntityFilter && /* @__PURE__ */ jsxs(Popover, { children: [
        /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { variant: "outline", "data-testid": testIds.filter, children: [
          /* @__PURE__ */ jsx(Filter, { className: "mr-2 h-4 w-4" }),
          filters.entityName ? (_a = accessibleEntities.find((e) => e.slug === filters.entityName)) == null ? void 0 : _a.names.singular : "All Types"
        ] }) }),
        /* @__PURE__ */ jsx(PopoverContent, { className: "w-[200px] p-0", children: /* @__PURE__ */ jsx(Command, { children: /* @__PURE__ */ jsx(CommandList, { children: /* @__PURE__ */ jsxs(CommandGroup, { children: [
          /* @__PURE__ */ jsx(CommandItem, { onSelect: () => handleFilterChange({}), children: "All Types" }),
          accessibleEntities.map((entity) => /* @__PURE__ */ jsxs(
            CommandItem,
            {
              onSelect: () => handleFilterChange({ entityName: entity.slug }),
              children: [
                React.createElement(entity.icon, { className: "mr-2 h-4 w-4" }),
                entity.names.singular
              ]
            },
            entity.slug
          ))
        ] }) }) }) })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { "data-testid": testIds.results, "data-cy": createCyId("search", "results"), children: [
      isSearching && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex items-center justify-center py-8", children: [
        /* @__PURE__ */ jsx(Loader2, { className: "h-6 w-6 animate-spin text-muted-foreground mr-2" }),
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "Searching..." })
      ] }) }),
      !isSearching && query && results.length === 0 && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "text-center py-8", children: [
        /* @__PURE__ */ jsx(Search, { className: "h-12 w-12 text-muted-foreground/50 mx-auto mb-4" }),
        /* @__PURE__ */ jsx("h3", { className: "text-lg font-medium mb-2", children: "No results found" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Try adjusting your search terms or filters" })
      ] }) }),
      results.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-3", children: results.map((result) => /* @__PURE__ */ jsx(
        Card,
        {
          className: "cursor-pointer hover:shadow-md transition-shadow",
          onClick: () => handleResultClick(result),
          "data-testid": testIds.result(result.id),
          "data-cy": createCyId("search", "result"),
          children: /* @__PURE__ */ jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
            React.createElement(result.entityConfig.icon, {
              className: "h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5"
            }),
            /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2 mb-1", children: [
                /* @__PURE__ */ jsx("h4", { className: "font-medium text-sm truncate", children: result.title }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 flex-shrink-0", children: [
                  /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: result.entityConfig.names.singular }),
                  /* @__PURE__ */ jsx(ExternalLink, { className: "h-3 w-3 text-muted-foreground" })
                ] })
              ] }),
              result.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mb-2 line-clamp-2", children: result.description }),
              result.matches.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                result.matches.slice(0, 2).map((match, index) => /* @__PURE__ */ jsxs("div", { className: "text-xs", children: [
                  /* @__PURE__ */ jsxs("span", { className: "font-medium text-muted-foreground", children: [
                    match.fieldLabel,
                    ":",
                    " "
                  ] }),
                  /* @__PURE__ */ jsx("span", { className: "text-foreground", children: highlightMatches(
                    match.value.length > 80 ? match.value.substring(0, 80) + "..." : match.value,
                    match.highlights
                  ) })
                ] }, index)),
                result.matches.length > 2 && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
                  "+",
                  result.matches.length - 2,
                  " more matches"
                ] })
              ] }),
              result.metadata.createdAt && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 mt-2 text-xs text-muted-foreground", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsx(Calendar, { className: "h-3 w-3" }),
                  formatDate(result.metadata.createdAt)
                ] }),
                result.metadata.createdBy && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsx(User, { className: "h-3 w-3" }),
                  result.metadata.createdBy
                ] })
              ] })
            ] })
          ] }) })
        },
        `${result.entityName}-${result.id}`
      )) })
    ] })
  ] });
}
function EntitySearchModal({
  isOpen,
  onClose,
  onResultClick,
  entities
}) {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: `fixed inset-0 z-50 ${isOpen ? "block" : "hidden"}`,
      "data-cy": "search-modal",
      children: [
        /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-background/80 backdrop-blur-sm", onClick: onClose }),
        /* @__PURE__ */ jsxs("div", { className: "fixed left-[50%] top-[50%] translate-x-[-50%] translate-y-[-50%] w-full max-w-2xl max-h-[80vh] bg-background border rounded-lg shadow-lg overflow-hidden", children: [
          /* @__PURE__ */ jsx("div", { className: "border-b p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium", children: "Search Everything" }),
            /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: onClose, children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) })
          ] }) }),
          /* @__PURE__ */ jsx("div", { className: "p-4 overflow-auto max-h-[calc(80vh-80px)]", children: /* @__PURE__ */ jsx(
            EntitySearch,
            {
              entities,
              variant: "inline",
              onResultClick: (result) => {
                onResultClick == null ? void 0 : onResultClick(result);
                onClose();
              },
              enableEntityFilter: true,
              maxResults: 50
            }
          ) })
        ] })
      ]
    }
  );
}
export {
  EntitySearch,
  EntitySearchModal
};
