import { TabPanel, ToggleControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { useResponsiveTab } from "./ResponsiveTabContext";

const ResponsiveControl = ({
  children,
  initialOpen = true,
  enableResponsiveToggle = false,
  responsiveEnabled = false,
  onResponsiveToggle = null,
  attributes = null,
  setAttributes = null,
  syncAttributeName = "responsiveEnabled",
}) => {
  const { activeTab, setActiveTab } = useResponsiveTab();

  const isResponsiveEnabled = enableResponsiveToggle ? responsiveEnabled : true;

  const handleToggleChange = (value) => {
    if (onResponsiveToggle) {
      onResponsiveToggle(value);
    }

    if (setAttributes && attributes) {
      setAttributes({ [syncAttributeName]: value });

      if (!value && activeTab === "sp") {
        setActiveTab("pc");
      }
    }
  };

  return (
    <div>
      {enableResponsiveToggle && (
        <div>
          <ToggleControl label={__("Responsive Settings", "zenblocks")} checked={isResponsiveEnabled} onChange={handleToggleChange} />
        </div>
      )}

      {isResponsiveEnabled ? (
        <TabPanel
          className="zenblocks-responsive-tab-panel"
          activeClass="zenblocks-tab--active"
          tabs={[
            { name: "pc", title: "PC", className: "zenblocks-tab zenblocks-tab--pc" },
            { name: "sp", title: "SP", className: "zenblocks-tab zenblocks-tab--sp" },
          ]}
          onSelect={setActiveTab}
          selected={activeTab}
          initialOpen={initialOpen}
        >
          {(tab) => children(tab.name)}
        </TabPanel>
      ) : (
        <div>{children("pc")}</div>
      )}
    </div>
  );
};

export default ResponsiveControl;
