import {
  Card,
  Form,
  FormLayout,
  TextField,
  Button,
  ResourceList,
  ResourceItem,
  Avatar,
  TextStyle,
  Icon,
  Modal,
  TextContainer
} from '@shopify/polaris';

import {
  CircleAlertMajorMonotone,
  CircleDotsMajorMonotone,
  CircleTickMajorMonotone
} from '@shopify/polaris-icons';

import React from 'react';
import moment from 'moment';
import Cookies from 'js-cookie';

import {Provider, Loading, Context} from '@shopify/app-bridge-react';

class OrderLogsCard extends React.Component {
  _interval;

  state = {
    limit : 10,
    offset : 0,
    where : {},
    total: 0,
    message: "error message here...",
    messageTitle: "Log from ...",
    messageShown: false,
    loading: true,
    items : []
  };

  shopOrgin = Cookies.get('shopOrigin');

  getLogs = () => {

    const {limit, offset, where} = this.state;

    const whereString = JSON.stringify(where);
    const data = { limit, offset, where };
    const fetchUrl = `/logs/order?limit=${limit}&offset=${offset}&where=${where}`;

    fetch(fetchUrl, {
        method: "GET",
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => {
        return response.json();
      })
      .then(json => {
        if(json.data){
          this.setState({
            loading: false,
            items: json.data,
            total: json.pagination && json.pagination.count
          });
        }
      });
  }

  openMessage = ( index ) => {
    const { items } = this.state;
    this.setState({
      message : items[index].message,
      messageTitle: `Log from ${items[index].orderId}`,
      messageShown : true,
    })
  }

  closeMessage = () => {
    this.setState({
      messageShown : false
    })
  }

  componentDidMount() {
    this.getLogs();
    this._interval = window.setInterval(this.getLogs, 5000);
  }

  componentWillUnmount() {
    window.clearInterval(this._interval);
  }

  render() {
    const { items, loading, messageShown, message, messageTitle } = this.state;

    return (
              <Card title="Logs">
                <ResourceList
                  loading={loading}
                  resourceName={{singular: 'log', plural: 'logs'}}
                  items={items}
                  renderItem={(item, id, index) => {
                    const { orderId, type, status, updatedAt, createdAt} = item;
                    let media, actions, onClick, url;
                    switch(status){
                      case "success":
                          onClick = () => {
                            alert("download");
                          }
                          actions = [
                            {content: 'View order', url: `https://${this.shopOrgin}/admin/orders/${item.orderId}`, external:true},
                            {content: 'Download file', onAction: onClick}
                          ];
                          media = <Icon source={CircleTickMajorMonotone} color="green"/>;
                          break;
                      case "error":
                          onClick = () => {
                            this.openMessage(index);
                          }
                          actions = [
                            {content: 'View order', url: `https://${this.shopOrgin}/admin/orders/${item.orderId}`, external:true},
                            {content: 'View message', onAction: onClick}
                          ];
                          media = <Icon source={CircleAlertMajorMonotone} color="red"/>;
                          break;
                      case "started":
                          url =`https://${this.shopOrgin}/admin/orders/${item.orderId}`
                          actions = [
                            {content: 'View order', url: url, external:true}
                          ];
                          media = <Icon source={CircleDotsMajorMonotone} color="blue"/>;
                          break;
                    }

                    return (
                      <ResourceItem
                        id={id}
                        url={url}
                        external={true}
                        onClick={onClick}
                        media={media}
                        accessibilityLabel={`View details for ${orderId}`}
                        shortcutActions={actions}
                      >
                        <h3>
                          <TextStyle variation="strong">{orderId}</TextStyle>
                        </h3>
                        <div>{type}</div>
                        <div><TextStyle variation="subdued">{moment(updatedAt).format('MMMM Do YYYY, h:mm:ssa')}</TextStyle></div>
                      </ResourceItem>
                    );
                  }}
                />
                <Modal
                    open={messageShown}
                    onClose={this.closeMessage}
                    title={messageTitle}
                  >
                    <Modal.Section>
                      <TextContainer>
                        <ul>
                            {message.split("\n").map((line, index)=>{
                              return <li key={index}>{line}</li>
                            })}
                        </ul>
                      </TextContainer>
                    </Modal.Section>
                  </Modal>
              </Card>
      );
  }

}

export default OrderLogsCard;
