import React, { useEffect, useState } from "react";
import AvatarGroup from "../AvatarGroup/AvatarGroup";
import PinnedIcon from "../../../../../assets/pinnedIcon.svg";
import SearchIcon from "../../../../../assets/searchIcon.svg";
import CloseIcon from "../../../../../assets/close.svg";
import UserPlusIcon from "../../../../../assets/userPlusIcon1.svg";
import { Menu } from "../../../../Menu";
import ThreedotIcon from "../../../../../assets/treedotIcon.svg";
import { ChatNotificationSettings } from "../ChatNotificationSettings/ChatNotificationSettings";
import { Button } from "../../../../Button";
import { Input } from "../../../../Input";
import SearchIconMaterial from "@mui/icons-material/Search";

import CloseIconMaterial from "@mui/icons-material/Close";
import { chartConfig } from "../../chatConfig";
const ChatHeaderAction = ({
  enableSearch,
  messageSearchValue,
  handleOpenMessageSearch,
  handleCloseMessageSearch,
  handleMessageSearchChange,

  onParticipantsClick,
  participants,
  onPinnedClick,
  threeDotMenuOptions,
  showNotificationSettings,
  handleNotificationSettingsClose,
  onThreeDotMenuClick,
  externalHandlers,
  isLoadingOptions,
  isSearching,
  filteredMenuOptions,
  menuSearchQuery,
  setMenuSearchQuery,
  renderCustomHeader,
  threeDotMenuOpen,
  onSaveNotification,
  selectedMenuItems,
  setSelectedMenuItems,
  handleThreeDotMenuClose,
  notificationSettings,
  maxAvatars = 2,
  selectedRadioOption,
  chatId,
  menuOptions,
  externalSavingMembers,
  ...restProps
}) => {
  const {
    showSearch = chartConfig.tableChatRightSectionConfig.tableChatHeaderConfig
      .showSearch,
    showPinned = chartConfig.tableChatRightSectionConfig.tableChatHeaderConfig
      .showPinned,
    showParticipants = chartConfig.tableChatRightSectionConfig
      .tableChatHeaderConfig.showParticipants,
    showThreeDotMenu = chartConfig.tableChatRightSectionConfig
      .tableChatHeaderConfig.showThreeDotMenu,
    className = chartConfig.tableChatRightSectionConfig.tableChatHeaderConfig
      .className,
    searchPlaceholder = chartConfig.tableChatRightSectionConfig
      .tableChatHeaderConfig.searchPlaceholder,
    isAddParticipantsAllowed = chartConfig.tableChatRightSectionConfig
      .tableChatHeaderConfig.isAddParticipantsAllowed,
  } = restProps;
  const [openMenu, setOpenMenu] = useState(false);
  const [threeDotAnchorEl, setThreeDotAnchorEl] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [isParticipantAdding, setIsParticipantAdding] = useState(false);
  const [isNotificationSettingsSaving, setIsNotificationSettingsSaving] =
    useState(false);
  const [participantsList, setParticipantsList] = useState([]);
  // const [selectedRadio, setSelectedRadio] = useState("existing");

  //   handle three dot menu click
  const handleThreeDotMenuClick = (event) => {
    onThreeDotMenuClick?.();
    setThreeDotAnchorEl(event.currentTarget);
  };

  // Handle participant icon click
  const handleParticipantsClick = async (event) => {
    try {
      setAnchorEl(event.currentTarget);
      setOpenMenu(true);

      // Call external handler to load initial participants
      if (externalHandlers?.onParticipantsClick) {
        await externalHandlers?.onParticipantsClick?.();
      }
    } catch (error) {
      console.error("Error loading participants:", error);
    }
  };

  const handleNotificationSettingsClick = async (data) => {
    try {
      setIsNotificationSettingsSaving(true);
      if (externalHandlers?.onNotificationSettingChange) {
        await externalHandlers?.onNotificationSettingChange?.(data);
      }
    } catch (error) {
      console.error("Error saving notification settings:", error);
    } finally {
      setIsNotificationSettingsSaving(false);
    }
  };

  const fetchParticipants = async (radioOption) => {
    if (externalHandlers?.loadParticipantsAvatar) {
      const participants = await externalHandlers?.loadParticipantsAvatar(
        radioOption || selectedRadioOption,
        chatId
      );
      setParticipantsList(participants);
    }
  };

  useEffect(() => {
    if (chatId || externalSavingMembers) {
      fetchParticipants("existing");
    }
  }, [chatId, externalSavingMembers, menuOptions?.length]);

  const handleParticipantAddOrRemove = async () => {
    try {
      setIsParticipantAdding(true);
      // Call external add participants handler
      if (externalHandlers?.onParticipantAdd) {
        const result = await externalHandlers.onParticipantAdd(
          selectedMenuItems,
          selectedRadioOption,
          chatId
        );
        await externalHandlers?.handleRadioButtonChange?.(selectedRadioOption);
      }
    } catch (error) {
      console.error("Error adding participants:", error);
    } finally {
      setIsParticipantAdding(false);
      setOpenMenu(false);
      setAnchorEl(null);
      externalHandlers?.onClose?.();
    }
  };

  return (
    <div
      className={`chat-header-right ${className} ${
        enableSearch ? "search-enabled" : ""
      }`}
    >
      {showSearch && (
        <div className="chat-search-container">
          {enableSearch ? (
            <div className="chat-search-input-container">
              <Input
                autoFocus
                type="text"
                placeholder={searchPlaceholder}
                value={messageSearchValue}
                onChange={(e) => handleMessageSearchChange(e)}
                width="100%"
                leftIcon={<SearchIconMaterial />}
                rightIcon={<CloseIconMaterial />}
                rightIconClick={handleCloseMessageSearch}
              />
            </div>
          ) : (
            <img
              src={SearchIcon}
              alt="search"
              onClick={handleOpenMessageSearch}
              className="search-icon"
            />
          )}
          {/* {enableSearch && (
            <>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="8"
                height="6"
                viewBox="0 0 8 6"
                fill="none"
              >
                <path
                  d="M7.8419 5.23362C7.7365 5.34448 7.6117 5.3999 7.46751 5.3999C7.3236 5.3999 7.19895 5.34448 7.09354 5.23362L4.00527 1.98558L0.906456 5.24471C0.808081 5.34817 0.685112 5.3999 0.537549 5.3999C0.389987 5.3999 0.263505 5.34448 0.158103 5.23362C0.0527009 5.12277 -1.31872e-09 4.99151 -1.80841e-09 4.83987C-2.29715e-09 4.68851 0.0527009 4.55741 0.158103 4.44655L3.71014 0.721841C3.75231 0.677499 3.79798 0.646017 3.84717 0.627393C3.89635 0.609066 3.94906 0.599901 4.00527 0.599901C4.06148 0.599901 4.11419 0.609066 4.16337 0.627393C4.21256 0.646017 4.25823 0.677499 4.30039 0.721841L7.85244 4.45764C7.95081 4.5611 8 4.68851 8 4.83987C8 4.99151 7.9473 5.12277 7.8419 5.23362Z"
                  fill="#60697D"
                />
              </svg>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="8"
                height="6"
                viewBox="0 0 8 6"
                fill="none"
              >
                <path
                  d="M0.158102 0.766378C0.263504 0.655524 0.3883 0.600096 0.53249 0.600096C0.676399 0.600096 0.801054 0.655524 0.906455 0.766378L3.99473 4.01441L7.09354 0.755294C7.19192 0.65183 7.31489 0.600098 7.46245 0.600098C7.61001 0.600098 7.7365 0.655525 7.8419 0.766379C7.9473 0.877234 8 1.00849 8 1.16013C8 1.31149 7.9473 1.44259 7.8419 1.55345L4.28985 5.27816C4.24769 5.3225 4.20202 5.35398 4.15283 5.3726C4.10364 5.39093 4.05094 5.40009 3.99473 5.40009C3.93851 5.40009 3.88581 5.39093 3.83663 5.3726C3.78744 5.35398 3.74176 5.3225 3.6996 5.27816L0.147562 1.54236C0.0491875 1.43889 -1.22122e-07 1.31149 -9.61396e-08 1.16013C-7.01065e-08 1.00848 0.0527005 0.877232 0.158102 0.766378Z"
                  fill="#60697D"
                />
              </svg>
            </>
          )} */}
        </div>
      )}

      {showPinned && (
        <div className="chat-pinned">
          <Button
            className="pinned_img"
            icon={<img src={PinnedIcon} className="participants-img" />}
            iconPlacement="left"
            size="large"
            type="default"
            variant="tertiary"
            onClick={onPinnedClick}
          />
        </div>
      )}

      {showParticipants && (
        <div className="chat-participants">
          <div className="chat-participants-container">
            {participantsList?.length > 0 && (
              <div>
                <AvatarGroup
                  avatars={participantsList}
                  maxAvatars={maxAvatars} // Show only 3 avatars
                  size="sm"
                />
              </div>
            )}
            {isAddParticipantsAllowed ? (
              <>
                <Button
                  className="btn_border participants-button "
                  icon={<img src={UserPlusIcon} className="participants-img" />}
                  iconPlacement="left"
                  size="small"
                  type="default"
                  variant="tertiary"
                  onClick={handleParticipantsClick}
                  aria-label={`View all ${participants.length} participants`}
                />

                <Menu
                  anchorEl={anchorEl}
                  iconPlacement="left"
                  menuContainerClassName="participants-menu-container"
                  MenuProps={{
                    anchorOrigin: {
                      vertical: "bottom",
                      horizontal: "left",
                    },
                    transformOrigin: {
                      vertical: "top",
                      horizontal: "right",
                    },
                  }}
                  open={openMenu}
                  onClose={() => {
                    setOpenMenu(false);
                    externalHandlers?.onClose?.();
                  }}
                  primaryButtonProps={{
                    loading: isParticipantAdding,
                    disabled: isParticipantAdding,
                    label: selectedRadioOption === "new" ? "Add" : "Remove",
                  }}
                  onTertiaryButtonClick={() => {
                    setOpenMenu(false);
                    externalHandlers?.onClose?.();
                  }}
                  onPrimaryButtonClick={handleParticipantAddOrRemove}
                  options={filteredMenuOptions}
                  selected="add"
                  withActionButtons
                  withCheckbox
                  // Custom header with radio buttons and search
                  renderCustomHeader={renderCustomHeader}
                  filteredOptions={filteredMenuOptions}
                  searchQuery={menuSearchQuery}
                  onSearchChange={(value) => {
                    // setMenuSearchQuery(value);
                    externalHandlers?.onSearchChange?.(value);
                  }}
                  onSelectAll={(allValues) => {
                    setSelectedMenuItems(allValues);
                    externalHandlers?.onSelectAll?.(allValues);
                  }}
                  onClearSelection={() => {
                    setSelectedMenuItems([]);
                    externalHandlers?.onClearSelection?.();
                  }}
                  customHeaderProps={{
                    selectedItems: selectedMenuItems,
                    externalHandlers: {
                      // ...externalHandlers,
                      // onRadioButtonChange: async (value) => {
                      //   console.log("onRadioButtonChange", value);
                      //   handleRadioChange(value);
                      // },
                    },
                    isLoading: isLoadingOptions,
                    isSearching: isSearching,
                    onSelectionChange: (newSelection) => {
                      setSelectedMenuItems(newSelection);
                      externalHandlers?.onSelectionChange?.(newSelection);
                    },
                  }}
                />
              </>
            ) : null}
          </div>
        </div>
      )}
      {showThreeDotMenu ? (
        <Button
          className="chat-header-right-button btn_border_participant "
          icon={<img src={ThreedotIcon} />}
          iconPlacement="left"
          size="small"
          type="default"
          variant="tertiary"
          onClick={handleThreeDotMenuClick}
        />
      ) : null}

      <Menu
        anchorEl={threeDotAnchorEl}
        iconPlacement="left"
        open={threeDotMenuOpen}
        onClose={() => {
          handleThreeDotMenuClose?.();
        }}
        MenuProps={{
          anchorOrigin: {
            vertical: "bottom",
            horizontal: "left",
          },
          transformOrigin: {
            vertical: "top",
            horizontal: "right",
          },
        }}
        menuContainerClassName="three-dot-menu-container"
        // onOptionClick={handleThreeDotOptionClick}
        options={threeDotMenuOptions}
        selected="add"
      />

      {/* Notification Settings */}
      <ChatNotificationSettings
        isOpen={showNotificationSettings}
        isLoading={isNotificationSettingsSaving}
        onClose={handleNotificationSettingsClose}
        onSaveNotification={handleNotificationSettingsClick}
        notificationSettings={notificationSettings}
      />
    </div>
  );
};

export default ChatHeaderAction;
