import { Button, TextInput } from "@sc/components/ui";
import _ from "lodash";
import React, { Component } from "react";

export default class SEO extends Component {
  constructor(props) {
    super(props);

    this.state = {
      title: "",
      keywords: "",
      description: ""
    };

    this.handleChange = this.handleChange.bind(this);
    this.saveSettings = this.saveSettings.bind(this);
  }

  async componentDidMount() {
    const { getPageQuery, match } = this.props;

    const pageId = match.params.nodeId;
    const { data } = await getPageQuery.refetch({ pageId });

    console.log({ data });
    const { pageSettings } = data.page;

    this.setState({
      ..._.get(pageSettings, "seo", {})
    });
    // console.log({ data });
  }

  handleChange(key, value) {
    this.setState({
      [key]: value
    });
  }

  async saveSettings() {
    const { updatePageSettings, getPageQuery, history, match } = this.props;
    const { title, keywords, description } = this.state;

    const { pageSettings, id } = getPageQuery.page;

    const variables = {
      pageId: id,
      pageSettings: {
        ...pageSettings,
        seo: {
          title,
          keywords,
          description
        }
      }
    };

    await updatePageSettings({ variables });

    history.push(
      `/campaign/${match.params.campaignId}/${match.params.nodeId}/builder`
    );
  }

  render() {
    return (
      <div>
        <TextInput
          label="Page Title"
          value={this.state.title}
          onChange={event => {
            this.handleChange("title", event.target.value);
          }}
        />
        <TextInput
          label="Page Keywords"
          value={this.state.keywords}
          onChange={event => {
            this.handleChange("keywords", event.target.value);
          }}
        />
        <TextInput
          label="Page Description"
          value={this.state.description}
          multiline
          onChange={event => {
            this.handleChange("description", event.target.value);
          }}
        />
        <div style={{ padding: 20, textAlign: "center" }}>
          <Button primary large onClick={this.saveSettings}>
            Save Settings
          </Button>
        </div>
      </div>
    );
  }
}
