import React, { useEffect, useState, useCallback } from "react";

import { MenuOptionsHeader } from "../../../../Menu/MenuHeaderInfo";

// Debounce utility function
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

import "./chatHeader.styles.scss";
import ChatHeaderInfo from "./ChatHeaderInfo";
import ChatHeaderAction from "./ChatHeaderAction";
import ActiveNotificationIcon from "../../../../../assets/active-notificationIcon.svg";
import { chartConfig } from "../../chatConfig";

export const ChatHeader = ({
  title,
  chatId,
  participants = [],
  className = "chat-header",
  participantsList,
  onSaveNotification,
  createdBy,
  createdAt,
  chatHeaderConfig = {},
  ...restProps
}) => {
  const [enableSearch, setEnableSearch] = useState(false);
  const [threeDotMenuOpen, setThreeDotMenuOpen] = useState(false);
  // New state for testing external handlers
  const [menuSearchQuery, setMenuSearchQuery] = useState("");
  const [selectedMenuItems, setSelectedMenuItems] = useState([]);
  const [messageSearchValue, setMessageSearchValue] = useState("");

  // Async loading states
  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(() => {
    if (chatHeaderConfig?.headerConfig?.selectedRadioOptionMenu) {
      setSelectedRadioOption(
        chatHeaderConfig?.headerConfig?.selectedRadioOptionMenu ||
          chartConfig.userConfig.radioButtonConfig.selectedRadioOption
      );
    }
  }, [chatHeaderConfig?.headerConfig?.selectedRadioOptionMenu]);

  // Three-dot menu and notification states
  const [showNotificationSettings, setShowNotificationSettings] =
    useState(false);

  // Function to fetch options based on radio selection
  const fetchOptionsForRadio = async (radioValue) => {
    try {
      console.log(`🔄 [API] Loading options for ${radioValue}...`);
      setIsLoadingOptions(true);
      setMenuOptions([]);
      setSelectedMenuItems([]); // Clear selections when changing categories
      setMenuSearchQuery(""); // Clear search when changing categories
      setLoadingError(null);

      // Call external handler to load options
      const options = await chatHeaderConfig?.loadParticipants?.(
        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);
    }
  };

  // Handle search with debouncing
  useEffect(() => {
    let isSubscribed = true; // For cleanup

    const performSearch = async () => {
      if (!menuSearchQuery.trim()) {
        setSearchResults([]);
        setIsSearching(false);
        return;
      }

      setIsSearching(true);
      setLoadingError(null);

      try {
        // Try external search handler first
        if (chatHeaderConfig?.onSearchChange) {
          const results = await chatHeaderConfig.onSearchChange(
            menuSearchQuery,
            selectedRadioOption,
            chatId
          );

          if (isSubscribed) {
            setSearchResults(results || []);
          }
        } else {
          const filteredResults = menuOptions.filter((option) => {
            // Search in label (main display text)
            const labelMatch = option.label
              ?.toLowerCase()
              .includes(menuSearchQuery.toLowerCase());

            // Search in other properties if they exist
            const emailMatch = option.otherProps?.email
              ?.toLowerCase()
              .includes(menuSearchQuery.toLowerCase());
            const userCodeMatch = option.otherProps?.user_code
              ?.toString()
              .includes(menuSearchQuery);

            // Return true if any property matches
            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]); // Remove chatHeaderConfig from dependencies

  // Determine which options to show
  const getOptionsToShow = () => {
    if (isLoadingOptions) {
      return []; // Show empty while loading
    }

    if (menuSearchQuery.trim()) {
      return isSearching ? [] : searchResults; // Show search results or empty while searching
    }

    return menuOptions; // Show initial loaded options
  };

  const filteredMenuOptions = getOptionsToShow();

  // Radio button change handler
  const handleRadioButtonChange = async (value) => {
    setSelectedRadioOption(value);
    setMenuSearchQuery("");
    await fetchOptionsForRadio(value);
  };

  // Local handlers for menu header
  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);

    if (optionId === "notifications") {
      // Close three-dot menu and open notification settings
      setThreeDotMenuOpen(false);
      setShowNotificationSettings(true);
    } else {
      // Handle other menu options
      switch (optionId) {
        case "account":
          console.log("Opening account settings...");
          break;
        case "preferences":
          console.log("Opening preferences...");
          break;
        case "help":
          console.log("Opening help & support...");
          break;
        case "about":
          console.log("Opening about...");
          break;
        default:
          console.log("Unknown option:", optionId);
      }
    }
  };

  const threeDotMenuOptions = [
    {
      id: "notifications",
      label: "Notifications",
      icon: <img src={ActiveNotificationIcon} alt="notification" />,
      onClick: () => {
        handleThreeDotMenuOptionClick("notifications");
      },
    },
  ];

  const handleNotificationSettingsClose = () => {
    setShowNotificationSettings(false);
  };

  // Message search handlers
  const handleEnableMessageSearch = () => {
    setEnableSearch(true);
  };
  const handleCloseMessageSearch = () => {
    setEnableSearch(false);
    setMessageSearchValue("");

    // Clear search results
    if (chatHeaderConfig?.onSearchClear) {
      chatHeaderConfig.onSearchClear();
    }
  };

  // Debounced search handler
  const debouncedSearch = useCallback(
    debounce(async (searchValue, chatId) => {
      if (chatHeaderConfig?.onSearchMessage) {
        await chatHeaderConfig.onSearchMessage(searchValue, chatId);
      }
    }, 500),
    [chatHeaderConfig?.onSearchMessage]
  );

  const handleMessageSearchChange = async (e) => {
    const searchValue = e.target.value;
    setMessageSearchValue(searchValue);

    // Call the debounced search handler
    debouncedSearch(searchValue, chatId);
  };

  // pinned click handler
  const handlePinnedClick = () => {
    chatHeaderConfig?.onPinnedClick?.(chatId);
  };
  // participants click handler
  const handleParticipantsClick = async () => {
    if (chatHeaderConfig?.onParticipantsClick) {
      await chatHeaderConfig.onParticipantsClick(chatId);
    }
    if (menuOptions.length === 0 && selectedRadioOption) {
      await fetchOptionsForRadio(selectedRadioOption);
    }
  };

  // three dot menu click handler
  const handleThreeDotMenuClose = () => {
    setThreeDotMenuOpen(false);
  };

  const handleThreeDotMenuClick = () => {
    setThreeDotMenuOpen(true);
  };

  // save notification settings handler
  const handleSaveNotificationSettings = (data) => {
    console.log("[ChatHeader] handleSaveNotificationSettings", data);
    onSaveNotification?.(data);
    chatHeaderConfig?.onNotificationSettingChange?.(data);
  };

  const CleanupParticipantsData = () => {
    console.log("[ChatHeader] CleanupParticipantsData");
    setMenuOptions([]);
    setSelectedMenuItems([]);
    setMenuSearchQuery("");
    // setSelectedRadioOption(chatHeaderConfig?.headerConfig?.selectedRadioOption);
    setIsLoadingParticipants(false);
    setIsLoadingOptions(false);
    setIsSearching(false);
    setSearchResults([]);
    setLoadingError(null);
  };

  // Custom header render function for testing
  const renderCustomHeader = (headerProps) => {
    return (
      <MenuOptionsHeader
        {...headerProps}
        externalHandlers={localHandlers}
        customHeaderProps={{
          searchPlaceholder: "Search in here...",
          selectAllLabel: "Select all",
          clearButtonText: "Clear",
          radioButtonProps: {},
          searchInputProps: {
            style: { fontSize: "14px" },
          },
        }}
        overrideConfig={{
          isSearchable: true,
          isSelectAllAllowed: true,
          showRadioButton: true,
          radioButtonOptions: chatHeaderConfig?.headerConfig?.radioOptions,
          selectedRadioButton: selectedRadioOption,
        }}
      />
    );
  };

  return (
    <div className={`chat-header ${className}`}>
      {!enableSearch ? (
        <ChatHeaderInfo
          title={title}
          chatId={chatId}
          createdBy={createdBy}
          createdAt={createdAt}
        />
      ) : null}
      <ChatHeaderAction
        // Basic props
        chatId={chatId}
        enableSearch={enableSearch}
        messageSearchValue={messageSearchValue}
        participants={participants}
        // Loading states
        isLoadingOptions={isLoadingOptions}
        isSearching={isSearching}
        isLoadingParticipants={isLoadingParticipants}
        loadingError={loadingError}
        // Search handlers
        handleOpenMessageSearch={handleEnableMessageSearch}
        handleMessageSearchChange={handleMessageSearchChange}
        handleCloseMessageSearch={handleCloseMessageSearch}
        menuSearchQuery={menuSearchQuery}
        setMenuSearchQuery={setMenuSearchQuery}
        // Menu and options
        threeDotMenuOpen={threeDotMenuOpen}
        threeDotMenuOptions={threeDotMenuOptions}
        handleThreeDotMenuClose={handleThreeDotMenuClose}
        filteredMenuOptions={filteredMenuOptions}
        selectedMenuItems={selectedMenuItems}
        setSelectedMenuItems={setSelectedMenuItems}
        // Action handlers
        onPinnedClick={handlePinnedClick}
        onThreeDotMenuClick={handleThreeDotMenuClick}
        onSaveNotification={handleSaveNotificationSettings}
        // Notification settings
        showNotificationSettings={showNotificationSettings}
        handleNotificationSettingsClose={handleNotificationSettingsClose}
        // Custom rendering
        renderCustomHeader={renderCustomHeader}
        // External handlers and config
        externalHandlers={{
          onSearchChange: (value) => {
            // Update local state first
            setMenuSearchQuery(value);
            // Then call external handler if it exists
            if (chatHeaderConfig?.onSearchChange) {
              chatHeaderConfig.onSearchChange(value);
            }
          },
          onSelectAll: localHandlers.onSelectAll,
          onClearSelection: localHandlers.onClearSelection,
          onSelectionChange: (newSelection) => {
            setSelectedMenuItems(newSelection);
          },
          onParticipantsClick: handleParticipantsClick,
          loadMenuOptions: chatHeaderConfig?.loadMenuOptions,
          menuOptions: menuOptions,
          // loadParticipants: chatHeaderConfig?.loadParticipants,
          onClose: CleanupParticipantsData,
          onParticipantAdd: chatHeaderConfig?.onParticipantAdd,
          onNotificationSettingChange:
            chatHeaderConfig?.onNotificationSettingChange,
          onSearchMessage: handleMessageSearchChange,
          participantsList: chatHeaderConfig?.participantsList,
          loadParticipantsAvatar: chatHeaderConfig?.loadParticipantsAvatar,
          handleRadioButtonChange: handleRadioButtonChange,
        }}
        notificationSettings={chatHeaderConfig?.notificationSettings}
        // Pass through any additional props
        {...restProps}
        {...chatHeaderConfig?.headerConfig}
        selectedRadioOption={selectedRadioOption}
        menuOptions={menuOptions}
        externalSavingMembers={chatHeaderConfig?.externalSavingMembers}
      />
    </div>
  );
};
