import React, { useEffect, useState } from "react";
import { Tabs } from "../Tabs";
import { Button } from "../Button";
import { RadioButtonGroup } from "../RadioButtonGroup";
import { TableColsIcon, TableFormatIcon } from "./tableIcons";
import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
import ViewColumnOutlinedIcon from "@mui/icons-material/ViewColumnOutlined";
import FormatColorTextOutlinedIcon from "@mui/icons-material/FormatColorTextOutlined";

export default function TableSettings({
  showMenu,
  Columns,
  actualRef,
  tableFontSize,
  setTableFontSize,
  handleMenuClick,
  onNumberFormatChange,
  colDefs,
  setShowMenu,
  showTableSetting,
  setShowTableSetting,
  setTableSettingOpen,
  tableActions,
  onTableActionsTabClick,
  showFilterStrip,
  hideTableFormat,
  hideTableActions,
  savedViewsOptions,
  handleSaveAndApply,
  maxSavedViews,
  handleSavedViewClick,
  handleEditSaveView,
  isSaveViewEnabled,
  isSavingViewLoading,
  handleDeleteViewClick,
  isDeleteViewLoading,
  handleSetDefaultView,
  hideNumericFormat,
  hideFontSize,
  customTabInTableSettings,
  saveViewCustomFilter,
  customRenderSaveViewContent,
  onTableSettingClick,
  deleteViewPromptText,
  tableSettingsTitle = "Table Settings",
  registerTableSettingToggle,
  numericFormatDefault,
}) {
  const [selectedMenuTab, setSelectedMenuTab] = useState("Columns");

  const [numericFormat, setNumericFormat] = useState(
    numericFormatDefault || "full_no"
  );
  const onFontSizeChange = (val) => {
    setTableFontSize(val);
  };

  const onNumericFormatChange = (val) => {
    setNumericFormat(val);
    onNumberFormatChange(val);
  };

  useEffect(() => {
    setNumericFormat(numericFormatDefault);
  }, [numericFormatDefault]);
  //style={{ display: showMenu ? "block" : "none" }}

  const tabPanels = [
    <Columns
      ref={actualRef}
      column={colDefs}
      showMenu={showMenu}
      savedViewsOptions={savedViewsOptions}
      handleSaveAndApply={handleSaveAndApply}
      maxSavedViews={maxSavedViews}
      handleSavedViewClick={handleSavedViewClick}
      handleEditSaveView={handleEditSaveView}
      isSaveViewEnabled={isSaveViewEnabled}
      isSavingViewLoading={isSavingViewLoading}
      handleDeleteViewClick={handleDeleteViewClick}
      isDeleteViewLoading={isDeleteViewLoading}
      handleSetDefaultView={handleSetDefaultView}
      saveViewCustomFilter={saveViewCustomFilter}
      customRenderSaveViewContent={customRenderSaveViewContent}
      deleteViewPromptText={deleteViewPromptText}
    />,
    !hideTableFormat && (
      <TableFormat
        tableFontSize={tableFontSize}
        onFontSizeChange={onFontSizeChange}
        numericFormat={numericFormat}
        onNumericFormatChange={onNumericFormatChange}
        hideNumericFormat={hideNumericFormat}
        hideFontSize={hideFontSize}
      />
    ),
    !hideTableActions && <TableActions tableActions={tableActions} />,
    ...(Array.isArray(customTabInTableSettings)
      ? customTabInTableSettings.map((tab) => tab?.tabPanels)
      : []),
  ].filter(Boolean);

  const tabNames = [
    {
      label: selectedMenuTab === "Columns" ? "Columns" : "",
      value: "Columns",
      icon: <ViewColumnOutlinedIcon fontSize="small" />,
    },
    !hideTableFormat && {
      label: selectedMenuTab === "Format" ? "Format" : "",
      value: "Format",
      icon: <FormatColorTextOutlinedIcon fontSize="small" />,
    },
    !hideTableActions && {
      label: selectedMenuTab === "Actions" ? "Actions" : "",
      value: "Actions",
      icon: <AutoFixHighIcon />,
    },
    ...(Array.isArray(customTabInTableSettings)
      ? customTabInTableSettings.map((tab) => ({
          ...tab.tabNames,
          label:
            selectedMenuTab === tab?.tabNames?.value
              ? tab?.tabNames?.label
              : "",
        }))
      : []),
  ].filter(Boolean);

  const onCloseTableSetting = (e) => {
    setSelectedMenuTab("Columns");
    setShowMenu(false);
    setShowTableSetting(false);
    setTableSettingOpen(false);
    onTableSettingClick(false);
  };

  // Expose a toggle function to the parent through a registration prop.
  // Parent can call the registered function as:
  //   toggle(open?: boolean, tabName?: "Columns" | "Format" | "Actions" | string, options?: { menuOnly?: boolean })
  // - If 'open' is undefined, it toggles based on current visibility.
  // - If 'tabName' is provided while opening, the specified tab will be selected.
  useEffect(() => {
    if (typeof registerTableSettingToggle === "function") {
      const toggle = (open, tabName, options = {}) => {
        const shouldOpen =
          typeof open === "undefined" ? !showTableSetting : Boolean(open);
        if (shouldOpen) {
          if (options?.menuOnly) {
            setShowMenu(true);
            // Do not open the full table settings panel in menuOnly mode
          } else {
            setShowMenu(true);
            setShowTableSetting(true);
            setTableSettingOpen(true);
            if (tabName) {
              setSelectedMenuTab(tabName);
            }
            onTableSettingClick(true);
          }
        } else {
          if (options?.menuOnly) {
            // Close only the menu, keep the table settings panel state unchanged
            setShowMenu(false);
          } else {
            onCloseTableSetting();
          }
        }
      };
      registerTableSettingToggle(toggle);
    }
  }, [
    registerTableSettingToggle,
    showTableSetting,
    setShowMenu,
    setShowTableSetting,
    setTableSettingOpen,
    onTableSettingClick,
  ]);

  return (
    <div
      className={`table-setting-main-container ${
        showTableSetting ? "display-table-setting" : ""
      } ${showFilterStrip ? "filters-strip-visible" : ""}`}
    >
      <div className="table-setting-header">
        <h2>{tableSettingsTitle}</h2>
        <span
          role="button"
          className="close_icon"
          onClick={onCloseTableSetting}
          tabIndex={0}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              onCloseTableSetting();
            }
          }}
        />
      </div>
      <Tabs
        value={selectedMenuTab}
        onChange={(_event, val) => {
          setSelectedMenuTab(val);
          if (val === "Actions") {
            onTableActionsTabClick();
          }
        }}
        tabPanels={tabPanels}
        tabNames={tabNames}
        remountOnTabChange={false}
      />
    </div>
  );
}

const TableFormat = ({
  tableFontSize,
  onFontSizeChange,
  numericFormat,
  onNumericFormatChange,
  hideNumericFormat,
  hideFontSize,
}) => {
  return (
    <div className="table-setting-format-settings">
      {!hideFontSize && (
        <div className="table-setting-font-size-setting-container">
          <h3 className="custom-menu-sub-header">Font size</h3>
          <RadioButtonGroup
            value={tableFontSize}
            onChange={(_e, val) => {
              onFontSizeChange(val);
            }}
            options={[
              {
                label: "Small",
                value: "small",
              },
              {
                label: "Medium (default)",
                value: "medium",
              },
              {
                label: "Large",
                value: "large",
              },
            ]}
            selectedOption="medium"
          />
        </div>
      )}
      {!hideNumericFormat && (
        <div className="table-setting-number-format-setting-container">
          <h3 className="custom-menu-sub-header">Numeric Values</h3>
          <RadioButtonGroup
            value={numericFormat}
            onChange={(_e, val) => {
              onNumericFormatChange(val);
            }}
            options={[
              {
                label: "Full Number",
                value: "full_no",
              },
              {
                label: "In K (Thousands)",
                value: "thou",
              },
              {
                label: "In M (Millions)",
                value: "mil",
              },
              {
                label: "In B (Billions)",
                value: "bil",
              },
            ]}
            selectedOption="full_no"
          />
        </div>
      )}
    </div>
  );
};

const TableActions = ({ tableActions }) => {
  return (
    <div className="table-setting-action-settings">
      <div className="table-setting-action-container">{tableActions}</div>
    </div>
  );
};
