import { Button, ToolbarButton, ToolbarGroup } from '@wordpress/components';
import { useState, useMemo, Fragment } from '@wordpress/element';
import { LKSProductCardControlProps } from '../type';
import { LKSProductCard } from './LKSProductCard';
import { getStatic } from '@/utils';
import { AddProductModal } from '../components/add-products-modal';
import { PLUGIN_NAME } from '@/constants';
import { BlockControls } from '@wordpress/block-editor';

const PREFIX = 'lks-product-card__edit';

export const LKSProductCardEdit = ({
  isSelected,
  attributes,
  setAttributes,
}: LKSProductCardControlProps & { isSelected: boolean }) => {
  const [modalVisible, setModalVisible] = useState(false);

  const isEmptyProducts = useMemo(
    () => !attributes.products.length,
    [attributes.products],
  );

  const toolbarButtonText = useMemo(() => {
    const icon = isEmptyProducts ? 'plus-alt2' : 'edit-large';
    const label = isEmptyProducts ? 'Add Products' : 'Edit Products';
    return {
      icon,
      label,
    } as const;
  }, [isEmptyProducts]);

  return (
    <Fragment>
      {isSelected && (
        <BlockControls>
          <ToolbarGroup>
            <ToolbarButton
              icon={toolbarButtonText.icon}
              label={toolbarButtonText.label}
              onClick={() => setModalVisible(true)}
            >
              {toolbarButtonText.label}
            </ToolbarButton>
          </ToolbarGroup>
        </BlockControls>
      )}
      <div className={PREFIX}>
        {isEmptyProducts ? (
          <div className={`${PREFIX}__empty`}>
            <div className={`${PREFIX}__empty__header`}>
              <img
                className={`${PREFIX}__empty__header__logo`}
                src={getStatic('/images/logo.png')}
              />
              <div className={`${PREFIX}__empty__header__title`}>
                {PLUGIN_NAME}
              </div>
            </div>
            <div className={`${PREFIX}__empty__body`}>
              <Button
                variant="primary"
                onClick={() => setModalVisible(true)}
                className={`${PREFIX}__empty__body__btn lks-button`}
              >
                Add Products
              </Button>
            </div>
          </div>
        ) : (
          <LKSProductCard isEdit {...attributes} />
        )}
        <AddProductModal
          visible={modalVisible}
          attributes={attributes}
          setAttributes={setAttributes}
          onClose={() => setModalVisible(false)}
        />
      </div>
    </Fragment>
  );
};
