import { jsxs, jsx } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from "react";
import { MenuHeaderInfo } from "../../../../Menu/MenuHeaderInfo.js";
/* empty css                       */
import ChatHeaderAction from "./ChatHeaderAction.js";
import ChatHeaderInfo from "./ChatHeaderInfo.js";
import { getAssetUrl } from "../../../../../utils/assetBase.js";
import { chartConfig } from "../../chatConfig.js";
const ActiveNotificationIcon = getAssetUrl("icons/active-notificationIcon.svg");
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}
const ChatHeader = ({
  title,
  chatId,
  participants = [],
  className = "chat-header",
  participantsList,
  onSaveNotification,
  createdBy,
  createdAt,
  chatHeaderConfig = {},
  ...restProps
}) => {
  var _a;
  const [enableSearch, setEnableSearch] = useState(false);
  const [threeDotMenuOpen, setThreeDotMenuOpen] = useState(false);
  const [menuSearchQuery, setMenuSearchQuery] = useState("");
  const [selectedMenuItems, setSelectedMenuItems] = useState([]);
  const [messageSearchValue, setMessageSearchValue] = useState("");
  const [menuOptions, setMenuOptions] = useState([]);
  const [isLoadingOptions, setIsLoadingOptions] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [searchResults, setSearchResults] = useState([]);
  const [selectedRadioOption, setSelectedRadioOption] = useState("");
  const [isLoadingParticipants, setIsLoadingParticipants] = useState(false);
  const [loadingError, setLoadingError] = useState(null);
  useEffect(() => {
    var _a2, _b;
    if ((_a2 = chatHeaderConfig.headerConfig) == null ? void 0 : _a2.selectedRadioOptionMenu) {
      setSelectedRadioOption(
        ((_b = chatHeaderConfig.headerConfig) == null ? void 0 : _b.selectedRadioOptionMenu) || chartConfig.userConfig.radioButtonConfig.selectedRadioOption
      );
    }
  }, [(_a = chatHeaderConfig.headerConfig) == null ? void 0 : _a.selectedRadioOptionMenu]);
  const [showNotificationSettings, setShowNotificationSettings] = useState(false);
  const fetchOptionsForRadio = async (radioValue) => {
    var _a2;
    try {
      console.log(`🔄 [API] Loading options for ${radioValue}...`);
      setIsLoadingOptions(true);
      setMenuOptions([]);
      setSelectedMenuItems([]);
      setMenuSearchQuery("");
      setLoadingError(null);
      const options = await ((_a2 = chatHeaderConfig.loadParticipants) == null ? void 0 : _a2.call(chatHeaderConfig, radioValue, chatId));
      if (options) {
        console.log(`✅ [API] ${radioValue} options loaded successfully`);
        setMenuOptions(options);
      }
    } catch (error) {
      console.error(`❌ [API] Error loading options for ${radioValue}:`, error);
      setLoadingError(`Failed to load options for ${radioValue}`);
    } finally {
      setIsLoadingOptions(false);
    }
  };
  useEffect(() => {
    let isSubscribed = true;
    const performSearch = async () => {
      if (!menuSearchQuery.trim()) {
        setSearchResults([]);
        setIsSearching(false);
        return;
      }
      setIsSearching(true);
      setLoadingError(null);
      try {
        if (chatHeaderConfig.onSearchChange) {
          const results = await chatHeaderConfig.onSearchChange(
            menuSearchQuery,
            selectedRadioOption,
            chatId
          );
          if (isSubscribed) {
            setSearchResults(results || []);
          }
        } else {
          const filteredResults = menuOptions.filter((option) => {
            var _a2, _b, _c, _d, _e;
            const labelMatch = (_a2 = option.label) == null ? void 0 : _a2.toLowerCase().includes(menuSearchQuery.toLowerCase());
            const emailMatch = (_c = (_b = option.otherProps) == null ? void 0 : _b.email) == null ? void 0 : _c.toLowerCase().includes(menuSearchQuery.toLowerCase());
            const userCodeMatch = (_e = (_d = option.otherProps) == null ? void 0 : _d.user_code) == null ? void 0 : _e.toString().includes(menuSearchQuery);
            return labelMatch || emailMatch || userCodeMatch;
          });
          if (isSubscribed) {
            setSearchResults(filteredResults);
          }
        }
      } catch (error) {
        if (isSubscribed) {
          setLoadingError("Failed to perform search");
          setSearchResults([]);
        }
      } finally {
        if (isSubscribed) {
          setIsSearching(false);
        }
      }
    };
    const debounceTimer = setTimeout(performSearch, 300);
    return () => {
      isSubscribed = false;
      clearTimeout(debounceTimer);
    };
  }, [menuSearchQuery, selectedRadioOption]);
  const getOptionsToShow = () => {
    if (isLoadingOptions) {
      return [];
    }
    if (menuSearchQuery.trim()) {
      return isSearching ? [] : searchResults;
    }
    return menuOptions;
  };
  const filteredMenuOptions = getOptionsToShow();
  const handleRadioButtonChange = async (value) => {
    setSelectedRadioOption(value);
    setMenuSearchQuery("");
    await fetchOptionsForRadio(value);
  };
  const localHandlers = {
    onSelectAll: (allValues) => {
      if (allValues.length === selectedMenuItems.length) {
        setSelectedMenuItems([]);
      } else {
        setSelectedMenuItems(allValues || filteredMenuOptions.map((opt) => opt.value));
      }
    },
    onClearSelection: () => {
      console.log("External clear selection handler [ChatHeader]");
      setSelectedMenuItems([]);
    },
    onRadioButtonChange: (value) => {
      console.log("📻 [External] Radio button change: [ChatHeader]", value);
      handleRadioButtonChange(value);
    },
    onMenuOptionChange: (value) => {
      console.log("External:[Menu Option] [ChatHeader]", value);
    }
  };
  const handleThreeDotMenuOptionClick = (optionId) => {
    console.log("Three-dot menu option clicked:", optionId);
    {
      setThreeDotMenuOpen(false);
      setShowNotificationSettings(true);
    }
  };
  const threeDotMenuOptions = [
    {
      id: "notifications",
      label: "Notifications",
      icon: /* @__PURE__ */ jsx("img", { alt: "notification", src: ActiveNotificationIcon }),
      onClick: () => {
        handleThreeDotMenuOptionClick("notifications");
      }
    }
  ];
  const handleNotificationSettingsClose = () => {
    setShowNotificationSettings(false);
  };
  const handleEnableMessageSearch = () => {
    setEnableSearch(true);
  };
  const handleCloseMessageSearch = () => {
    setEnableSearch(false);
    setMessageSearchValue("");
    if (chatHeaderConfig.onSearchClear) {
      chatHeaderConfig.onSearchClear();
    }
  };
  const debouncedSearch = useCallback(
    debounce(async (searchValue, chatId2) => {
      if (chatHeaderConfig.onSearchMessage) {
        await chatHeaderConfig.onSearchMessage(searchValue, chatId2);
      }
    }, 500),
    [chatHeaderConfig.onSearchMessage]
  );
  const handleMessageSearchChange = async (e) => {
    const searchValue = e.target.value;
    setMessageSearchValue(searchValue);
    debouncedSearch(searchValue, chatId);
  };
  const handlePinnedClick = () => {
    var _a2;
    (_a2 = chatHeaderConfig.onPinnedClick) == null ? void 0 : _a2.call(chatHeaderConfig, chatId);
  };
  const handleParticipantsClick = async () => {
    if (chatHeaderConfig.onParticipantsClick) {
      await chatHeaderConfig.onParticipantsClick(chatId);
    }
    if (menuOptions.length === 0 && selectedRadioOption) {
      await fetchOptionsForRadio(selectedRadioOption);
    }
  };
  const handleThreeDotMenuClose = () => {
    setThreeDotMenuOpen(false);
  };
  const handleThreeDotMenuClick = () => {
    setThreeDotMenuOpen(true);
  };
  const handleSaveNotificationSettings = (data) => {
    var _a2;
    console.log("[ChatHeader] handleSaveNotificationSettings", data);
    onSaveNotification == null ? void 0 : onSaveNotification(data);
    (_a2 = chatHeaderConfig.onNotificationSettingChange) == null ? void 0 : _a2.call(chatHeaderConfig, data);
  };
  const CleanupParticipantsData = () => {
    console.log("[ChatHeader] CleanupParticipantsData");
    setMenuOptions([]);
    setSelectedMenuItems([]);
    setMenuSearchQuery("");
    setIsLoadingParticipants(false);
    setIsLoadingOptions(false);
    setIsSearching(false);
    setSearchResults([]);
    setLoadingError(null);
  };
  const renderCustomHeader = (headerProps) => {
    var _a2;
    return /* @__PURE__ */ jsx(
      MenuHeaderInfo,
      {
        ...headerProps,
        customHeaderProps: {
          searchPlaceholder: "Search in here...",
          selectAllLabel: "Select all",
          clearButtonText: "Clear",
          radioButtonProps: {},
          searchInputProps: {
            style: { fontSize: "14px" }
          }
        },
        externalHandlers: localHandlers,
        overrideConfig: {
          isSearchable: true,
          isSelectAllAllowed: true,
          showRadioButton: true,
          radioButtonOptions: (_a2 = chatHeaderConfig.headerConfig) == null ? void 0 : _a2.radioOptions,
          selectedRadioButton: selectedRadioOption
        }
      }
    );
  };
  return /* @__PURE__ */ jsxs("div", { className: `chat-header ${className}`, children: [
    !enableSearch ? /* @__PURE__ */ jsx(ChatHeaderInfo, { chatId, createdAt, createdBy, title }) : null,
    /* @__PURE__ */ jsx(
      ChatHeaderAction,
      {
        chatId,
        enableSearch,
        externalHandlers: {
          onSearchChange: (value) => {
            setMenuSearchQuery(value);
            if (chatHeaderConfig == null ? void 0 : chatHeaderConfig.onSearchChange) {
              chatHeaderConfig.onSearchChange(value);
            }
          },
          onSelectAll: localHandlers.onSelectAll,
          onClearSelection: localHandlers.onClearSelection,
          onSelectionChange: (newSelection) => {
            setSelectedMenuItems(newSelection);
          },
          onParticipantsClick: handleParticipantsClick,
          loadMenuOptions: chatHeaderConfig == null ? void 0 : chatHeaderConfig.loadMenuOptions,
          menuOptions,
          // loadParticipants: chatHeaderConfig?.loadParticipants,
          onClose: CleanupParticipantsData,
          onParticipantAdd: chatHeaderConfig == null ? void 0 : chatHeaderConfig.onParticipantAdd,
          onNotificationSettingChange: chatHeaderConfig == null ? void 0 : chatHeaderConfig.onNotificationSettingChange,
          onSearchMessage: handleMessageSearchChange,
          participantsList: chatHeaderConfig == null ? void 0 : chatHeaderConfig.participantsList,
          loadParticipantsAvatar: chatHeaderConfig == null ? void 0 : chatHeaderConfig.loadParticipantsAvatar,
          handleRadioButtonChange
        },
        filteredMenuOptions,
        handleCloseMessageSearch,
        handleMessageSearchChange,
        handleThreeDotMenuClose,
        isLoadingParticipants,
        isSearching,
        menuSearchQuery,
        messageSearchValue,
        selectedMenuItems,
        threeDotMenuOptions,
        onThreeDotMenuClick: handleThreeDotMenuClick,
        handleNotificationSettingsClose,
        renderCustomHeader,
        loadingError,
        handleOpenMessageSearch: handleEnableMessageSearch,
        notificationSettings: chatHeaderConfig == null ? void 0 : chatHeaderConfig.notificationSettings,
        ...restProps,
        participants,
        isLoadingOptions,
        setMenuSearchQuery,
        threeDotMenuOpen,
        setSelectedMenuItems,
        onPinnedClick: handlePinnedClick,
        onSaveNotification: handleSaveNotificationSettings,
        showNotificationSettings,
        ...chatHeaderConfig == null ? void 0 : chatHeaderConfig.headerConfig,
        externalSavingMembers: chatHeaderConfig == null ? void 0 : chatHeaderConfig.externalSavingMembers,
        menuOptions,
        selectedRadioOption
      }
    )
  ] });
};
export {
  ChatHeader
};
