/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */
import { __ } from "@wordpress/i18n";
import { useMemo, useContext } from "@wordpress/element";
import { Spinner, RangeControl } from "@wordpress/components";
import { useEntityProp } from "@wordpress/core-data";

/**
 * Internal dependencies
 */
import { Widget, Fieldset, SaveActions, useHandleSave } from "sdk/components";
import { DataContext } from "../../data";

const getBreakpointValue = (prefix, breakpoints, fallback) => {
  if (!breakpoints) {
    return fallback;
  }

  const item = breakpoints.find((item) => prefix === item?.prefix);
  return item && item?.breakpoint ? item.breakpoint : fallback;
};

const Breakpoints = () => {
  const { Messages } = useContext(DataContext);

  const [breakpoints, setBreakpoints] = useEntityProp(
    "root",
    "site",
    "CBBBreakpoints",
  );

  const onBreakpointChange = (prefix, breakpoints) => (value) => {
    const newBreakpoints = breakpoints.map((item) => {
      if (item.prefix === prefix) {
        return { ...item, breakpoint: value };
      }

      return item;
    });

    setBreakpoints(newBreakpoints);
  };

  const tablet = useMemo(
    () => getBreakpointValue("md", breakpoints, 768),
    [breakpoints],
  );
  const desktop = useMemo(
    () => getBreakpointValue("lg", breakpoints, 1024),
    [breakpoints],
  );

  const { handleSave, MessageNotice } = useHandleSave(Messages);

  return (
    <Widget
      title={__("Manage reponsive breakpoints", "content-blocks-builder")}
      renderFooter={() => <SaveActions onSave={handleSave} />}
    >
      <Fieldset className="fieldset">
        <div className="fieldset__label">
          <strong>
            {__(
              "Change the breakpoint values for phone, tablet and desktop. All values are in pixels (px).",
              "content-blocks-builder",
            )}
          </strong>
        </div>
        {!breakpoints ? (
          <Spinner />
        ) : (
          <>
            <RangeControl
              label={__("Tablet", "content-blocks-builder")}
              value={tablet}
              onChange={onBreakpointChange("md", breakpoints)}
              min={600}
              max={1200}
            />
            <RangeControl
              label={__("Desktop", "content-blocks-builder")}
              value={desktop}
              onChange={onBreakpointChange("lg", breakpoints)}
              min={960}
              max={1920}
            />
          </>
        )}
      </Fieldset>
      <MessageNotice />
    </Widget>
  );
};

export default Breakpoints;
