import PropTypes from "prop-types";
import React, { Component } from "react";
import { Section } from "..";
import { ButtonLinkGroup } from "../RichEditor/ButtonGroups";

/**
 * A dropdown menu of FancySelectors
 */
class LinkDropDown extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isExpanded: props.isExpanded,
    };

    this.toggleExpansion = this.toggleExpansion.bind(this);
    this.doChange = this.doChange.bind(this);
  }

  toggleExpansion() {
    this.setState((prevState) => ({ isExpanded: !prevState.isExpanded }));
  }

  doChange(url) {
    const { settings, updateComponentSettings } = this.props;

    if (this.props.hasOwnProperty("onChange")) {
      this.props.onChange(url);
    } else {
      updateComponentSettings(settings.id, {
        ...settings,
        href: url,
      });
    }
  }

  render() {
    const { isExpanded } = this.state;
    return (
      <Section
        label={this.props.label || "Link"}
        icon="link"
        isExpanded={isExpanded}
      >
        <ButtonLinkGroup
          {...this.props}
          linkSelector={false}
          linkSelectorExpanded={false}
          linkCrosshair={false}
          showCloseButton={false}
          onChange={(url) => this.doChange(url)}
        />
      </Section>
    );
  }
}

LinkDropDown.propTypes = {
  /** This is the text that will appear inside of the dropdown menu */
  text: PropTypes.string.isRequired,
  /** This event is triggered when the URL is changed */
  onChange: PropTypes.func.isRequired,
  /** These are the <FancySelector /> elements that are collapsed inside of the dropdown element */
  children: PropTypes.element.isRequired,
  /** Bool if the dropdown should be collapsed or expanded */
  isExpanded: PropTypes.bool.isRequired,
};

LinkDropDown.defaultProps = {
  text: "Links to: ",
  isExpanded: false,
};

export default LinkDropDown;
