import * as React from 'react';
import { FormattedMessage } from 'react-intl';
import { Layout, Button, ButtonType } from 'twitch-core-ui';

import { ClientOnly } from 'mweb/common/containers/clientOnly';
import { Location } from 'mweb/common/reducers/app';
import { TrackingProps, withTracking } from 'mweb/common/tracking/withTracking';
import { ShareSheet } from 'mweb/common/components/shareSheet';

export const INTERACTION_CONTENT_SHARE = 'share';

export interface ShareButtonValueProps {
  shareSheetHeader: string;
  title: string;
  appLocation: Location;
}

export interface ShareButtonDispatchProps {
  handleShare: (medium: string, location: Location) => void;
}

interface ShareButtonState {
  sharingDockOpen: boolean;
}

export interface ShareButtonProps
  extends ShareButtonValueProps,
    ShareButtonDispatchProps,
    TrackingProps {}

export class ShareButtonBase extends React.Component<
  ShareButtonProps,
  ShareButtonState
> {
  constructor(props: ShareButtonProps) {
    super(props);
    this.state = { sharingDockOpen: false };
  }

  onToggleSharingDockButtonClick = (
    e: React.MouseEvent<HTMLButtonElement>,
  ): void => {
    if (e && e.currentTarget) {
      e.currentTarget.blur();
    }
    this.toggleSharingDock();
  };

  toggleSharingDock = (): void => {
    this.setState(prevState => ({
      ...prevState,
      sharingDockOpen: !prevState.sharingDockOpen,
    }));
  };

  render(): JSX.Element {
    return (
      <Layout>
        <ClientOnly hasLatencyTrackedChildren>
          <Button
            type={ButtonType.Hollow}
            onClick={this.props.trackClick(
              {
                interactionContent: INTERACTION_CONTENT_SHARE,
              },
              this.onToggleSharingDockButtonClick,
            )}
          >
            <FormattedMessage
              id="share-button--top-level-message"
              defaultMessage="Share"
            />
          </Button>
          <ShareSheet
            header={this.props.shareSheetHeader}
            isVisible={this.state.sharingDockOpen}
            title={this.props.title}
            appLocation={this.props.appLocation}
            toggleSharingDock={this.toggleSharingDock}
            handleShare={this.props.handleShare}
          />
        </ClientOnly>
      </Layout>
    );
  }
}

export const ShareButton = withTracking(ShareButtonBase);
