import * as React from "react";
import type { BlockSaveProps } from "@wordpress/blocks";
import { useBlockProps } from "@wordpress/block-editor";
import shortcode from "@wordpress/shortcode";
import { kebabCase, pick, pickBy } from "lodash";
import type { TitleSelection, WidgetParams } from "../types";

export const generateShortcode = (
	attributes: WidgetParams,
	options: {
		keyMap?: Record<string, string | null>;
		pretty?: boolean;
	} = {}
): string => {
	const { keyMap = {} } = options;
	const widgetKeys = [
    "id", "idType", "objectType", "seasonNumber", "episodeNumber",
    "maxOffers", "offerLabel", "apiKey", "theme", "scale", "noOffersMessage",
  ];

	// Filter out keys that are mapped to null in the keyMap
	const filteredWidgetKeys = widgetKeys.filter(key => keyMap[key] !== null);

	// Pick only the relevant attributes
	const widgetProps = pick(attributes, filteredWidgetKeys);

	// Filter out undefined or null values
	const filteredProps = pickBy(widgetProps, (value) => Boolean(value));

	// Map keys to shortcode attributes
	const mappedAttributes = Object.entries(filteredProps).reduce(
		(acc, [key, value]) => {
			const mappedKey = keyMap[key] || key;
			acc[kebabCase(mappedKey)] = value;

			return acc;
		},
		{} as Record<string, unknown>
	);

	// Strip values which keys are marked for removal
	const shortcodeAttributes = pickBy(mappedAttributes, (value, key) => {
		return !key.startsWith('__removed_');
	});

	return shortcode.string({
		tag: "justwatch",
		attrs: shortcodeAttributes,
		type: "single",
	});
};

export default ({
	attributes,
}: BlockSaveProps<TitleSelection>): JSX.Element => {
	const blockProps = useBlockProps.save();
	const { id, objectType } = attributes;

	const code = id && objectType
		? generateShortcode(attributes)
		: '';

	return <div {...blockProps}>{code}</div>;
};
