import React, { useState, useMemo, useEffect, useRef, Suspense } from "react";
import { Button } from "../Button";
import { Menu } from "../Menu";
import TableSettings from "./tableSettings";
import TableMoreOptions from "./tableMoreOptions";
import { Tooltip } from "../Tooltip";
import UnfoldLessDoubleIcon from "@mui/icons-material/UnfoldLessDouble";
import UnfoldMoreDoubleIcon from "@mui/icons-material/UnfoldMoreDouble";
// import ChatIcon from "../../assets/chat-icon.svg";
import { FiltersStrip } from "../FiltersStrip";
import Badge from "@mui/material/Badge";
import FilterAltOutlinedIcon from "@mui/icons-material/FilterAltOutlined";
import FilterAltOffOutlinedIcon from "@mui/icons-material/FilterAltOffOutlined";
import MoreHorizOutlinedIcon from "@mui/icons-material/MoreHorizOutlined";
import { Alert } from "../Alert";
import ChatIcon from "../../assets/chatIcon.svg";
import { lazy } from "react";
// const TableChatSidePanel = lazy(() =>
//   import("../TableChat/TableChatSidePanel")
// );
import TableChatSidePanel from "../TableChat/TableChatSidePanel";

export default function TableHeader({
  actualRef,
  colDefs,
  Columns,
  tableFontSize,
  setTableFontSize,
  rowHeight,
  setRowHeight,
  tableHeader,
  topRightOptions,
  topLeftOptions,
  onGlobalSearchClick,
  cardContainer,
  onNumberFormatChange,
  hideRowHeightOptionMenu,
  showDownloadButton,
  onDownloadButtonClick,
  closeButton,
  handleCloseButtonClick,
  additionalButtons,
  setTableSettingOpen,
  showHideEditableCells,
  handleShowHideEditableCells,
  topCenterOptions,
  showContentualFilter,
  showContentualFilterBadge,
  onContentualFilterClick,
  contentualFilterProps = {},
  contentualFilterComponent,
  tableActions,
  onTableActionsTabClick,
  hideTableFormat,
  hideTableActions,
  hideTableSetting,
  explicitlyCloseTableSetting,
  customSystemButton,
  isChatEnabled = true,
  handleChatClick = () => {},
  isChatOpen,
  handleChatClose,
  chatConfiguration,
  savedViewsOptions,
  handleSaveAndApply,
  maxSavedViews,
  handleSavedViewClick,
  handleEditSaveView,
  isSaveViewEnabled,
  isSavingViewLoading,
  handleDeleteViewClick,
  isDeleteViewLoading,
  handleSetDefaultView,
  isCommentFeatureEnabled,
  showCommentBadge,
  toggleCommentMode,
  commentMode,
  hideFontSize,
  hideNumericFormat,
  onContentDensityChange,
  isCommentResolvedAlertOpen,
  setIsCommentResolvedAlertOpen,
  showCommentPanel,
  setShowCommentPanel,
  customTabInTableSettings,
  closeTableSettingOnOutsideClick,
  saveViewCustomFilter,
  customRenderSaveViewContent,
  onTableSettingClick,
  deleteViewPromptText,
  contentualFilterOpenByDefault,
  tableSettingsTitle,
  registerTableSettingToggle,
  numericFormatDefault,
  viewPoint,
  disableContextualFilter,
  disableTableSettings,
  onAdvanceSortClick,
  advanceSortEnabled,
}) {
  // manages displaying table setting
  const [showMenu, setShowMenu] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const rowHeightMenuOpen = Boolean(anchorEl);
  const handleWidthButtonClick = (event) => setAnchorEl(event.currentTarget);
  const handleWidthButtonClose = () => setAnchorEl(null);
  const [showTableSetting, setShowTableSetting] = useState(false);
  const [showFilterStrip, setShowFilterStrip] = useState(
    contentualFilterOpenByDefault
  );
  const prevCommentsCountRef = useRef(0);
  const commentBtnRef = useRef(null);

  const onRowHeightChange = (val) => {
    setRowHeight(val);
    setTimeout(() => {
      actualRef?.current?.api?.resetRowHeights();
    }, 0);
    handleWidthButtonClose();
  };

  const handleMenuClose = () => {
    setSelectedMenuTab("Columns");
  };

  //
  const handleMenuClick = (e) => {
    document.body.style.overflowX = "hidden";
    e.stopPropagation();
    setShowMenu((prev) => !prev);
    setShowTableSetting(false);
    setTableSettingOpen(false);
    setTimeout(() => {
      document.body.style.overflowX = "unset";
    }, 200);
  };

  const toggleCommentPanel = () => {
    setShowCommentPanel((prev) => !prev);
  };
  const handleCommentClick = (e) => {
    e.stopPropagation();
    if (showTableSetting) {
      setShowMenu(false);
      setShowTableSetting(false);
      setTableSettingOpen(false);
    }
    toggleCommentMode();
    toggleCommentPanel();
  };

  useEffect(() => {
    if (!showCommentPanel && commentMode) {
      toggleCommentMode();
    } else if (!commentMode && showCommentPanel) {
      toggleCommentPanel();
    }
  }, [commentMode, showCommentPanel]);

  // When commentMode is active, focus the comment icon to trigger :focus styling
  useEffect(() => {
    const el =
      commentBtnRef.current ||
      document.querySelector('[data-icon="comment"][data-type="table-icon"]');
    if (!el) return;
    if (commentMode) {
      el.focus?.();
    } else {
      el.blur?.();
    }
  }, [commentMode]);

  const isGroupRows = useMemo(() => {
    const hasGroupRows = (cols) =>
      cols.some(
        (col) => col.rowGroup || (col.children && hasGroupRows(col.children))
      );
    return hasGroupRows(colDefs);
  }, [colDefs]);

  const handleClickOutside = (event) => {
    if (
      showMenu &&
      !showTableSetting &&
      !event.target.closest(".table-more-options-container")
    ) {
      setShowMenu(false);
    }
    if (
      closeTableSettingOnOutsideClick &&
      showTableSetting &&
      !event.target.closest(".table-setting-main-container") &&
      !event.target.closest(".table-more-options-container")
    ) {
      setShowTableSetting(false);
      setShowMenu(false);
      setTableSettingOpen(false);
    }
    if (
      showCommentPanel &&
      !event.target.closest(".MuiPopover-root") &&
      !event.target.closest(".impact-input-wrapper") &&
      !event.target.closest(".comment-panel-main-container") &&
      !event.target.closest(".table-more-options-container") &&
      !event.target.closest(".ag-body-viewport")
    ) {
      setShowCommentPanel(false);
    }
  };

  useEffect(() => {
    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [showMenu, showTableSetting, showCommentPanel]);

  const handleFilterClick = () => {
    setShowFilterStrip(!showFilterStrip);
    if (onContentualFilterClick) {
      onContentualFilterClick();
    }
  };

  // Check if any header content should be displayed
  const hasHeaderContent = useMemo(() => {
    return !!(
      tableHeader ||
      topLeftOptions ||
      topCenterOptions ||
      topRightOptions ||
      onGlobalSearchClick ||
      showContentualFilter ||
      showDownloadButton ||
      !hideTableSetting ||
      closeButton ||
      showFilterStrip ||
      contentualFilterComponent ||
      (contentualFilterProps &&
        Object.keys(contentualFilterProps).length > 0) ||
      isCommentFeatureEnabled
    );
  }, [
    tableHeader,
    topLeftOptions,
    topCenterOptions,
    topRightOptions,
    onGlobalSearchClick,
    showContentualFilter,
    showDownloadButton,
    hideTableSetting,
    closeButton,
    showFilterStrip,
    contentualFilterComponent,
    contentualFilterProps,
    isCommentFeatureEnabled,
  ]);

  // Don't render anything if no header content
  if (!hasHeaderContent) {
    return null;
  }

  return (
    <div
      className="impact-table-main-header"
      style={{
        flexDirection: showFilterStrip ? "column" : "row",
        alignItems: showFilterStrip ? "initial" : "center",
        justifyContent: "center",
        transition: "height 0.3s ease",
        position: "relative",
      }}
    >
      {/* Alert positioned outside the main header flow to prevent height changes */}
      {isCommentResolvedAlertOpen && (
        <div
          style={{
            position: "absolute",
            top: "12px",
            left: "50%",
            transform: "translateX(-50%)",
            zIndex: 1000,
          }}
        >
          <Alert
            title="Comment is resolved"
            severity="success"
            onClose={() => setIsCommentResolvedAlertOpen(false)}
          />
        </div>
      )}
      <div className="impact-table-main-header-container">
        <div className="impact-table-main-header-left">
          <div className="table-heading">{tableHeader}</div>
          {topLeftOptions}
        </div>
        <div className="impact-table-center-cta-container">
          {topCenterOptions}
        </div>
        <div className="right-table-cta-container">
          {topRightOptions}
          {isChatEnabled && (
            <Tooltip
              title={chatConfiguration?.tooltipConfig?.title || "New feature"}
              description={
                chatConfiguration?.tooltipConfig?.description ||
                '"Chat" allows you to collaborate with your companions on the go.'
              }
              variant="feature"
            >
              <Button
                data-icon="chat"
                data-type="table-icon"
                variant="tertiary"
                icon={<img src={ChatIcon} alt="chat" />}
                onClick={handleChatClick}
                className="table-chat-icon-button"
              />
            </Tooltip>
          )}
          {onGlobalSearchClick ? (
            <Button
              data-icon="table-search"
              data-type="table-icon"
              variant="secondary"
              onClick={onGlobalSearchClick}
            />
          ) : null}
          {topRightOptions && viewPoint !== "list" && (
            <div className="divider-line" />
          )}
          {showContentualFilter && (
            <Tooltip
              title={showFilterStrip ? "Hide filter" : "Show filter"}
              variant="tertiary"
            >
              <Badge variant="dot" invisible={!showContentualFilterBadge}>
                <Button
                  variant="text"
                  icon={
                    showFilterStrip ? (
                      <FilterAltOffOutlinedIcon />
                    ) : (
                      <FilterAltOutlinedIcon />
                    )
                  }
                  onClick={handleFilterClick}
                  disabled={disableContextualFilter}
                />
              </Badge>
            </Tooltip>
          )}
          {isCommentFeatureEnabled && (
            <Tooltip title="Comment" variant="tertiary">
              <Badge variant="dot" invisible={!showCommentBadge}>
                <Button
                  data-icon="comment"
                  data-type="table-icon"
                  variant="text"
                  ref={commentBtnRef}
                  aria-pressed={Boolean(commentMode)}
                  data-active={commentMode ? "true" : undefined}
                  onClick={handleCommentClick}
                />
              </Badge>
            </Tooltip>
          )}
          {showDownloadButton && (
            <Tooltip title="Download" variant="tertiary">
              <Button
                data-icon="download"
                data-type="table-icon"
                variant="secondary"
                onClick={onDownloadButtonClick}
              />
            </Tooltip>
          )}
          {customSystemButton && customSystemButton}
          {!hideTableSetting && (
            <Tooltip title="More" variant="tertiary">
              <Button
                variant="text"
                icon={<MoreHorizOutlinedIcon />}
                onClick={handleMenuClick}
                disabled={disableTableSettings}
              />
            </Tooltip>
          )}
          {closeButton && (
            <>
              <div className="divider-line" />
              <Button
                data-icon="close"
                data-type="table-icon"
                variant="url"
                onClick={handleCloseButtonClick}
              />
            </>
          )}
        </div>
      </div>
      <TableMoreOptions
        showMenu={showMenu}
        extraButtons={additionalButtons}
        hideRowHeightOptionMenu={hideRowHeightOptionMenu}
        setShowTableSetting={setShowTableSetting}
        onRowHeightChange={onRowHeightChange}
        rowHeight={rowHeight}
        setRowHeight={setRowHeight}
        isGroupRows={isGroupRows}
        actualRef={actualRef}
        Columns={Columns}
        handleMenuClick={handleMenuClick}
        tableFontSize={tableFontSize}
        setTableFontSize={setTableFontSize}
        onNumberFormatChange={onNumberFormatChange}
        colDefs={colDefs}
        setShowMenu={setShowMenu}
        showTableSetting={showTableSetting}
        setTableSettingOpen={setTableSettingOpen}
        showHideEditableCells={showHideEditableCells}
        handleShowHideEditableCells={handleShowHideEditableCells}
        tableActions={tableActions}
        onTableActionsTabClick={onTableActionsTabClick}
        showFilterStrip={showFilterStrip}
        hideTableFormat={hideTableFormat}
        hideTableActions={hideTableActions}
        explicitlyCloseTableSetting={explicitlyCloseTableSetting}
        savedViewsOptions={savedViewsOptions}
        handleSaveAndApply={handleSaveAndApply}
        maxSavedViews={maxSavedViews}
        handleSavedViewClick={handleSavedViewClick}
        handleEditSaveView={handleEditSaveView}
        isSaveViewEnabled={isSaveViewEnabled}
        isSavingViewLoading={isSavingViewLoading}
        handleDeleteViewClick={handleDeleteViewClick}
        isDeleteViewLoading={isDeleteViewLoading}
        handleSetDefaultView={handleSetDefaultView}
        hideFontSize={hideFontSize}
        hideNumericFormat={hideNumericFormat}
        onContentDensityChange={onContentDensityChange}
        customTabInTableSettings={customTabInTableSettings}
        saveViewCustomFilter={saveViewCustomFilter}
        customRenderSaveViewContent={customRenderSaveViewContent}
        onTableSettingClick={onTableSettingClick}
        deleteViewPromptText={deleteViewPromptText}
        tableSettingsTitle={tableSettingsTitle}
        registerTableSettingToggle={registerTableSettingToggle}
        numericFormatDefault={numericFormatDefault}
        onAdvanceSortClick={onAdvanceSortClick}
        advanceSortEnabled={advanceSortEnabled}
      />
      {showFilterStrip && (
        <div className="divider-line" style={{ paddingTop: "16px" }} />
      )}
      {showFilterStrip && (
        <div className="impact-table-header-filter-strip">
          {contentualFilterComponent ? (
            contentualFilterComponent
          ) : (
            <FiltersStrip {...contentualFilterProps} />
          )}
        </div>
      )}
      {/* <Suspense fallback={<div>Loading...</div>} /> */}
      {isChatEnabled && (
        <TableChatSidePanel
          isOpen={isChatOpen}
          handleClose={handleChatClose}
          chatConfiguration={chatConfiguration}
        />
      )}
    </div>
  );
}
