import { BaseControl, CheckboxControl } from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { useEffect, useMemo, useCallback } from '@wordpress/element';
import { LKSProductCardControlProps } from '../../type';
import {
  LKSProductCardInfoTypeList,
  LKSProductCardInfoTypeTextMap,
  LKS_PRODUCT_CARD_CARD_LAYOUT,
  LKSProductCardUpDownInfoDisplayMap,
  LKS_PRODUCT_CARD_INFO_TYPE,
} from '../../constants';

const PREFIX = `lks-product-card__information`;

export const InformationControl = ({
  attributes,
  setAttributes,
}: LKSProductCardControlProps) => {
  const instanceId = useInstanceId(InformationControl);
  const id = `inspector_${PREFIX}_${instanceId}`;

  const displayInfos = useMemo(
    () => LKSProductCardUpDownInfoDisplayMap[attributes.pictureSize],
    [attributes.pictureSize],
  );

  const informationOptions = useMemo(() => {
    return LKSProductCardInfoTypeList.map(type => {
      const label = LKSProductCardInfoTypeTextMap[type];
      const checked = attributes.showInfos.includes(type);
      const [_displayType, ...showInfos] = displayInfos;
      const disabled =
        !showInfos.includes(type) ||
        (attributes.cardLayout === LKS_PRODUCT_CARD_CARD_LAYOUT.UP_DOWN &&
          type === LKS_PRODUCT_CARD_INFO_TYPE.CATEGORY);
      return {
        type,
        label,
        checked,
        disabled,
      };
    });
  }, [attributes.showInfos, displayInfos, attributes.cardLayout]);

  const handleToggleCheckStatus = useCallback(
    (infoType: LKS_PRODUCT_CARD_INFO_TYPE, status: boolean) => {
      const nextShowInfos = status
        ? [...attributes.showInfos, infoType]
        : attributes.showInfos.filter(type => type !== infoType);
      setAttributes({ showInfos: Array.from(new Set(nextShowInfos)) });
    },
    [attributes.showInfos, setAttributes],
  );

  useEffect(() => {
    const [_displayType, ...showInfos] = displayInfos;
    if (attributes.showInfos.find(infoType => !showInfos.includes(infoType))) {
      const nextShowInfos = attributes.showInfos.filter(infoType =>
        showInfos.includes(infoType),
      );
      setAttributes({ showInfos: Array.from(new Set(nextShowInfos)) });
    }
  }, [displayInfos, attributes.showInfos, setAttributes]);

  if (attributes.cardLayout === LKS_PRODUCT_CARD_CARD_LAYOUT.LEFT_RIGHT)
    return null;

  return (
    <BaseControl
      __nextHasNoMarginBottom
      label="Information"
      id={id}
      className={PREFIX}
    >
      <div>
        {informationOptions.map(option => (
          <CheckboxControl
            key={option.type}
            checked={option.checked}
            disabled={option.disabled}
            label={option.label}
            onChange={status => handleToggleCheckStatus(option.type, status)}
          />
        ))}
      </div>
    </BaseControl>
  );
};
