import _ from "lodash";
import React, { Component } from "react";
import { Dialog, DialogBody, Grid, Cell, Button } from "@sc/components/ui";
import { client } from "@sc/api/gql";
import { getCampaignObject } from "@sc/api/gql/campaigns";

export default class SelectPagePopup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      object: null,
      campaignId: false,
      pageId: false
    };
  }

  async componentDidMount() {
    const { options } = this.props;

    // get object details from the database
    const objectInfo = await client.query({
      query: getCampaignObject,
      variables: { id: options.id }
    });

    const objectId = _.get(objectInfo, "data.object.settings.objectId", false);

    // get campaign, object, and page details
    const { data } = await client.query({
      query: getCampaignObject,
      variables: { id: objectId }
    });

    // console.log({ data });

    this.setState({
      object: _.get(data, "object"),
      campaignId: _.get(data, "object.campaign.id"),
      pageId: _.get(data, "object.page.id")
    });
  }

  render() {
    const { onClose } = this.props;
    const { campaignId, pageId, object } = this.state;

    if (_.get(object, "type") !== "PageComponent") return null;

    return (
      <Dialog {...this.props} style={{ width: 700 }} centered>
        <DialogBody>
          <h2>Would you like to edit {object.name}?</h2>
          <p>Note: You will be updating the original page, not a replica</p>
          <br />
          <Grid justify="space-evenly" style={{ width: 250, margin: "0 auto" }}>
            <Cell align="center">
              <a
                target="_blank"
                rel="noopener noreferrer"
                href={`/campaign/${campaignId}/${pageId}/builder`}
              >
                <Button onClick={onClose} large tertiary>
                  Proceed
                </Button>
              </a>
            </Cell>
            <Cell align="center">
              <Button
                onClick={onClose}
                large
                transparent
                style={{ color: "#333" }}
              >
                Cancel
              </Button>
            </Cell>
          </Grid>
        </DialogBody>
      </Dialog>
    );
  }
}
