import classnames from "classnames/dedupe";
import { __ } from "@wordpress/i18n";
import { addFilter } from "@wordpress/hooks";
import { createHigherOrderComponent } from "@wordpress/compose";
import { PanelBody, ToggleControl } from "@wordpress/components";
import {
  InspectorControls,
  RichText,
  getColorClassName,
  useBlockProps,
  __experimentalGetBorderClassesAndStyles as getBorderClassesAndStyles,
	__experimentalGetColorClassesAndStyles as getColorClassesAndStyles,
	__experimentalGetElementClassName,
} from "@wordpress/block-editor";
import domReady from "@wordpress/dom-ready";
import { unregisterBlockStyle } from "@wordpress/blocks";
import "./style.scss";
import "./editor.scss";

domReady(function () {
  unregisterBlockStyle("core/table", "regular");
  unregisterBlockStyle("core/table", "stripes");
});

const filterBlocks = (settings) => {
  if (settings.name !== "core/table") {
    return settings;
  }

  const newSettings = {
    ...settings,
    attributes: {
      ...settings.attributes,
      figureClass: {
        type: "string",
        default: "wp-block-table ",
        source: "attribute",
        attribute: "class",
        selector: "figure",
      },
      tableClass: {
        type: "string",
        default: "ucla-table ",
        source: "attribute",
        attribute: "class",
        selector: "table",
      },
      // tableBordered: {
      //   type: "boolean",
      //   default: false,
      // },
      tableResponsive: {
        type: "boolean",
        default: false,
      },
      tableStickyFirstColumn: {
        type: "boolean",
        default: false,
      },
    },
    save({ attributes }) {
      const {
        hasFixedLayout,
        head,
        body,
        foot,
        backgroundColor,
        caption,
        tableResponsive,
        tableStickyFirstColumn,
        tableClass,
        figureClass,
      } = attributes;
      const isEmpty = !head.length && !body.length && !foot.length;

      if (isEmpty) {
        return null;
      }
      const colorProps = getColorClassesAndStyles( attributes );
	    const borderProps = getBorderClassesAndStyles( attributes );
      const blockProps = useBlockProps.save();
      const tableClasses = addDSClassToBlock(attributes);
      const figureClasses = addWPClassToWrapper(attributes);
      const hasCaption = !RichText.isEmpty(caption);
      const Section = ({ type, rows }) => {
        if (!rows.length) {
          return null;
        }

        const Tag = `t${type}`;

        return (
          <Tag>
            {rows.map(({ cells }, rowIndex) => (
              <tr key={rowIndex}>
                {cells.map(({ content, tag, align, colspan, rowspan }, cellIndex) => {
                  const cellClasses = classnames({
                    [`has-text-align-${align}`]: align,
                  });
                  return (
                    <RichText.Content
                      className={cellClasses ? cellClasses : undefined}
                      data-align={align}
                      tagName={tag}
                      value={content}
                      key={cellIndex}
                      colSpan={ colspan }
										  rowSpan={ rowspan }
                      scope={
                        tag === "th"
                        ? "col"
                        : (tableStickyFirstColumn && cellIndex === 0)
                        ? "row" :
                        undefined
                      }
                    />
                  );
                })}
              </tr>
            ))}
          </Tag>
        );
      };
      return (
        <figure {...blockProps} className={figureClasses === "" ? undefined : figureClasses}>
          <table style={{ ...colorProps.style, ...borderProps.style }} className={classnames(tableClasses === "" ? undefined : tableClasses, borderProps.className, colorProps.className)}>
            <Section type="head" rows={head} />
            <Section type="body" rows={body} />
            <Section type="foot" rows={foot} />
          </table>
          {hasCaption && (
            <RichText.Content className={ __experimentalGetElementClassName( 'caption' ) } tagName="figcaption" value={caption} />
          )}
        </figure>
      );
    },
  };
  return newSettings;
};

addFilter(
  "blocks.registerBlockType",
  "ucla-wordpress-plugin/filter-block",
  filterBlocks
);

const addDSClassToBlock = (attributes) => {
  const { tableStickyFirstColumn, tableClass } = attributes;
  const tableClasses = classnames(tableClass.split(" "), {
    "ucla-table": true,
    "ucla-table__sticky-column": tableStickyFirstColumn,
  });
  return tableClasses;
};
const addWPClassToWrapper = (attributes) => {
  const { hasFixedLayout, tableResponsive, figureClass, backgroundColor } =
    attributes;
  const backgroundClass = getColorClassName(
    "background-color",
    backgroundColor
  );
  const figureClasses = classnames(
    figureClass.split(" ", backgroundClass, {
      "wp-block-table": true,
      "ucla-table__responsive": tableResponsive,
      "has-background": !!backgroundClass,
      "has-fixed-layout": hasFixedLayout,
    })
  );
  return figureClasses;
};

const tableClassControl = createHigherOrderComponent((BlockEdit) => {
  return (props) => {
    if ("core/table" !== props.name) {
      return <BlockEdit {...props} />;
    }
    const {
      tableResponsive,
      tableStickyFirstColumn,
      tableClass,
      figureClass,
    } = props.attributes;
    // let onChangeTableBordered = () => {
    //   props.setAttributes({
    //     tableBordered: !tableBordered,
    //     tableClass: classnames(tableClass, {
    //       "ucla-table__border": !tableBordered,
    //     }),
    //   });
    // };
    let onChangeTableResponsive = () => {
      props.setAttributes({
        tableResponsive: !tableResponsive,
        figureClass: classnames(figureClass, {
          "ucla-table__responsive": !tableResponsive,
        }),
      });
    };
    let onChangeStickyFirstColumn = () => {
      props.setAttributes({
        tableStickyFirstColumn: !tableStickyFirstColumn,
        tableClass: classnames(tableClass, {
          "ucla-table__sticky-column": !tableStickyFirstColumn,
        }),
      });
    };
    return (
      <>
        <div className="ucla-table">
          <BlockEdit {...props} />
        </div>
        <InspectorControls>
          <PanelBody title={__("Table classes")} initialOpen={true}>
            <ToggleControl
              __nextHasNoMarginBottom
              label={__("Responsive")}
              checked={!!tableResponsive}
              onChange={onChangeTableResponsive}
            />
            {/* <ToggleControl
              label={__("Bordered")}
              checked={!!tableBordered}
              onChange={onChangeTableBordered}
            /> */}
            <ToggleControl
              __nextHasNoMarginBottom
              label={__("Sticky First Column")}
              checked={!!tableStickyFirstColumn}
              onChange={onChangeStickyFirstColumn}
            />
          </PanelBody>
        </InspectorControls>
      </>
    );
  };
}, "tableClassControl");

addFilter("editor.BlockEdit", "ucla-wordpress-plugin/table", tableClassControl);
