import Dialog from "@mui/material/Dialog";
import List from "@mui/material/List";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import { useEffect, useMemo, useState } from "react";
import { searchGlobal } from "@/features/search/api";
import { SearchBox } from "@/shared/ui/SearchBox.jsx";

const maxMenuResults = 8;

export function SearchDialog({ menuItems = [], onClose, onSelect, open }) {
  const [keyword, setKeyword] = useState("");
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const menuResults = useMemo(() => searchMenus(menuItems, keyword), [keyword, menuItems]);
  const displayResults = useMemo(() => [...menuResults, ...results], [menuResults, results]);

  useEffect(() => {
    if (!open) {
      setKeyword("");
      setResults([]);
    }
  }, [open]);

  useEffect(() => {
    if (!open) {
      return undefined;
    }

    const timer = window.setTimeout(async () => {
      setLoading(true);
      try {
        const data = await searchGlobal(keyword);
        setResults(data || []);
      } catch {
        setResults([]);
      } finally {
        setLoading(false);
      }
    }, 180);

    return () => window.clearTimeout(timer);
  }, [keyword, open]);

  const selectResult = (item) => {
    onSelect(item);
    onClose();
  };

  return (
    <Dialog
      className="global-search-modal"
      fullWidth
      maxWidth="md"
      onClose={onClose}
      open={open}
      slotProps={{ paper: { className: "search-dialog" } }}
    >
      <div className="search-dialog__head">
        <SearchBox autoFocus className="search-dialog__input" value={keyword} onChange={setKeyword} placeholder="搜索菜单、用户、角色..." />
      </div>

      <List className="search-dialog__list" disablePadding>
        {displayResults.map((item) => (
          <ListItemButton className="search-dialog__item" key={`${item.type}-${item.id}`} onClick={() => selectResult(item)}>
            <ListItemText
              primary={item.title}
              secondary={`${item.type} / ${item.subtitle}`}
              slotProps={{
                primary: { className: "search-dialog__primary" },
                secondary: { className: "search-dialog__secondary" }
              }}
            />
          </ListItemButton>
        ))}
        {!displayResults.length ? <div className="search-dialog__empty">{loading ? "搜索中..." : "暂无匹配结果"}</div> : null}
      </List>
    </Dialog>
  );
}

export function searchMenus(items = [], keyword = "") {
  const normalizedKeyword = normalizeSearchText(keyword);
  if (!normalizedKeyword) {
    return [];
  }

  return flattenMenuResults(items)
    .filter((item) => item.searchText.includes(normalizedKeyword))
    .slice(0, maxMenuResults)
    .map(({ searchText: _searchText, ...item }) => item);
}

function flattenMenuResults(items = [], ancestors = []) {
  return items.flatMap((item) => {
    const label = item.label || item.title || item.code || "";
    const breadcrumb = [...ancestors, label].filter(Boolean);
    const target = item.path || findFirstMenuPath(item.children);
    const current = target
      ? [
          {
            id: item.code || item.id || breadcrumb.join("/"),
            searchText: normalizeSearchText([label, item.code, item.path].filter(Boolean).join(" ")),
            subtitle: breadcrumb.join(" / "),
            target,
            title: label,
            type: "菜单"
          }
        ]
      : [];

    return [...current, ...flattenMenuResults(item.children || [], breadcrumb)];
  });
}

function findFirstMenuPath(items = []) {
  for (const item of items) {
    if (item.path) {
      return item.path;
    }

    const childPath = findFirstMenuPath(item.children || []);
    if (childPath) {
      return childPath;
    }
  }

  return "";
}

function normalizeSearchText(value) {
  return String(value || "").trim().toLowerCase();
}
