import React, { ReactNode, useContext, useState } from 'react';
import { IconButton, Popover } from '@wix/design-system';
import { Add } from '@wix/wix-ui-icons-common';
import { ToolbarCollectionContext } from '../ToolbarCollectionContext';
import { classes } from './AddFieldColumnHeader.st.css.js';

export interface AddFieldColumnHeaderProps {
  children: ReactNode;
}

export const AddFieldColumnHeader = ({
  children,
}: AddFieldColumnHeaderProps) => {
  const collectionFieldsSource = useContext(
    ToolbarCollectionContext,
  )?.collectionFieldsSource;
  // TODO: fix when the schema source exposes the CMS modal
  const customColumnAddField = collectionFieldsSource?.fieldsSource
    .fieldManagement?.canAddFields
    ? () =>
        collectionFieldsSource.openFieldModal({
          origin: 'Custom columns panel',
        })
    : undefined;
  const [hovered, setHovered] = useState(false);

  if (!collectionFieldsSource) {
    return <>{children}</>;
  }

  return (
    <Popover
      shown={hovered}
      appendTo="window"
      placement="top-start"
      moveBy={{ x: -27, y: -47 }}
      interactive
      fluid
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className={classes.root}
      dataHook="add-field-popover"
    >
      <Popover.Element>
        <span className={classes.title}>{children}</span>
      </Popover.Element>
      <Popover.Content>
        <span className={classes.hoverBridge}>
          <IconButton
            size="tiny"
            skin="standard"
            priority="secondary"
            dataHook="add-field-column-header-button"
            onClick={(e) => {
              e.stopPropagation();
              customColumnAddField?.();
            }}
          >
            <Add />
          </IconButton>
        </span>
      </Popover.Content>
    </Popover>
  );
};
