text: import React, { useState, useEffect, useContext, useCallback } from "react";
  import {
    Card,
    Tabs,
    Frame,
    Loading,
    Page,
    Button,
    ProgressBar,
  } from "@shopify/polaris";
  import { getBrowserName } from "../utils";
  import { getSessionToken } from "@shopify/app-bridge-utils";
  import { AppBridgeContext } from "@shopify/app-bridge-react/context";
  import { Banner } from "@shopify/polaris";
  import SitemapOverview from "../components/SitemapOverview";
  import SitemapJobs from "../components/SitemapJobs";
  import ColumnMapping from "../components/ColumnMappings";
  import FailedJobs from "../components/FailedJobs";
  import Plans from "../components/Plans";
  import ToastComponent from "../components/Toast";
  import { Icon } from "@shopify/polaris";
  import { RefreshMajor } from "@shopify/polaris-icons";
  import { FooterHelp } from "@shopify/polaris";
  import Typography from "@material-ui/core/Typography";
  
  const Index = () => {
    const context = useContext(AppBridgeContext);
    const [selected, setSelected] = useState(0);
    const [apiKey, setApiKey] = useState("");
    const [eligibleForFreeTrial, setEligibleForFreeTrial] = useState(null);
    const [currentPlan, setCurrentPlan] = useState("");
    const [credits, setCredits] = useState(0);
    const [userId, setUserId] = useState(0);
    const [oneTimeSignInUrlLoading, setOnTimeSignInUrlLoading] = useState(false);
    const [banner, setBanner] = useState(null);
    const [remainingCredits, setRemainingCredits] = useState(0);
    const [logInButtonDisabled, setLogInButtonDisabled] = useState(true);
    const [toastActive, setToastActive] = useState(false);
  
    const tabs = [
      {
        id: "Sitemaps-Overview",
        content: "Sitemap overview",
        accessibilityLabel: "All customers",
        panelID: "sitemap-overview-content-1",
      },
      {
        id: "SitemapJobs-Overview",
        content: "Sitemap jobs",
        panelID: "sitemap-jobs-content-1",
      },
      {
        id: "History-Overview",
        content: "Column mapping",
        panelID: "column-mapping-content-1",
      },
      {
        id: "Failed-jobs",
        content: "Failed jobs",
        panelID: "settings-content-1",
      },
      {
        id: "Plans",
        content: "Plans",
        panelID: "settings-content-1",
      },
    ];
  
    const toggleToastActive = useCallback(
      () => setToastActive((toastActive) => !toastActive),
      []
    );
  
    const navigateToPlansTab = () => {
      setSelected(4);
    };
  
    const openInNewTab = (url) => {
      const newWindow = window.open(url, "_blank", "noopener,noreferrer");
      if (newWindow) newWindow.opener = null;
    };
  
    const webscraperLoginHandler = () => {
      setOnTimeSignInUrlLoading(true);
      const fetchUrl = `/api/webscraper/generate-one-time-sign-in-url/${userId}`;
      const method = "GET";
      getSessionToken(context).then((token) => {
        fetch(fetchUrl, {
          method: method,
          headers: { Authorization: `Bearer ${token}` },
        })
          .then((response) => response.json())
          .then((json) => {
            if (json.oneTimeSignInUrl !== undefined) {
              setOnTimeSignInUrlLoading(false);
              openInNewTab(json.oneTimeSignInUrl);
            }
          });
      });
    };
  
    const getRemainingCredits = (isSubscribed) => {
      const fetchUrl = `/api/webscraper/get-remaining-credits/${apiKey}/${userId}`;
      const method = "GET";
      getSessionToken(context).then((token) => {
        fetch(fetchUrl, {
          method: method,
          headers: { Authorization: `Bearer ${token}` },
        })
          .then((response) => response.json())
          .then((json) => {
            if (json.data && json.data.data !== undefined) {
              if (isSubscribed) {
                setRemainingCredits(json.data.data.page_credits);
              }
            }
          });
      });
    };
  
    const selectedContent = [
      <SitemapOverview
        navigateToPlansTab={navigateToPlansTab}
        key="SitemapOverview"
        apiKey={apiKey}
      />,
      <SitemapJobs key="SitemapJobs" navigateToPlansTab={navigateToPlansTab} />,
      <ColumnMapping
        key="ColumnMapping"
        navigateToPlansTab={navigateToPlansTab}
      />,
      <FailedJobs key="FailedJobs" navigateToPlansTab={navigateToPlansTab} />,
      <Plans
        key="Plans"
        eligibleForFreeTrial={eligibleForFreeTrial}
        currentPlan={currentPlan}
        userId={userId}
      />,
    ];
  
    const handleTabChange = useCallback((selectedTabIndex) => {
      setSelected(selectedTabIndex);
    }, []);
  
    useEffect(() => {
      let isSubscribed = true;
      const browser = getBrowserName();
      if (browser !== "Chrome" && browser !== "Firefox") {
        setBanner(
          <Banner
            title={`You are using ${browser}. Please use Google chrome or Mozilla firefox in
                    order to use webscraper shopify plugin.`}
            status="critical"
          />
        );
      } else {
        const fetchUrl = "/api/shop-data";
        const method = "GET";
        getSessionToken(context).then((token) => {
          fetch(fetchUrl, {
            method: method,
            headers: { Authorization: `Bearer ${token}` },
          })
            .then((response) => response.json())
            .then((json) => {
              if (json.data.currentPlan && json.data.userId === null) {
                setToastActive(true);
              }
              if (json.data.apiKey) {
                if (isSubscribed) {
                  setApiKey(json.data.apiKey);
                  setCurrentPlan(json.data.currentPlan);
                  setCredits(json.data.credits);
                  setUserId(json.data.userId);
                  setLogInButtonDisabled(false);
                }
              }
              if (json.data.eligibleForFreeTrial) {
                if (isSubscribed) {
                  setEligibleForFreeTrial(json.data.eligibleForFreeTrial);
                }
              }
            });
        });
      }
      return () => {
        isSubscribed = false;
      };
    }, []);
  
    useEffect(() => {
      let isSubscribed = true;
      getRemainingCredits(isSubscribed);
      return () => {
        isSubscribed = false;
      };
    }, [apiKey]);
  
    const creditsText = !remainingCredits
      ? "Credits: 0"
      : remainingCredits
      ? `Remaining Credits: ${remainingCredits}/${credits}`
      : null;
    const barProgress = !currentPlan
      ? 0
      : remainingCredits
      ? (remainingCredits / credits) * 100
      : !currentPlan
      ? 0
      : null;
    const remainingCreditsContent = (
      <Page
        title={creditsText}
        fullWidth
        primaryAction={
          <Button onClick={getRemainingCredits}>
            <Icon source={RefreshMajor} color="base" />
          </Button>
        }
      >
        <ProgressBar
          progress={Math.floor(barProgress)}
          color="primary"
          size="small"
        />
      </Page>
    );
  
    const pageContent = banner ? (
      banner
    ) : apiKey || !apiKey ? (
      <Page
        title="Web scraper"
        fullWidth
        primaryAction={
          <Button
            onClick={webscraperLoginHandler}
            primary
            loading={oneTimeSignInUrlLoading}
            disabled={logInButtonDisabled}
          >
            Log in to webscraper
          </Button>
        }
      >
        <Card>
          <Tabs tabs={tabs} selected={selected} onSelect={handleTabChange}>
            <Card.Section>{selectedContent[selected]}</Card.Section>
          </Tabs>
        </Card>
        <FooterHelp>
          <Typography variant="body2">
            Questions? Concerns? Requests? Send us a{" "}
            <a
              target="_blank"
              rel="noopener noreferrer"
              href="mailto:info@webscraper.io"
            >
              message
            </a>
          </Typography>
        </FooterHelp>
        <ToastComponent active={toastActive} toggleActive={toggleToastActive} />
      </Page>
    ) : (
      <Loading />
    );
  
    return (
      <Frame>
        {remainingCreditsContent}
        {pageContent}
      </Frame>
    );
  };
  
  export default Index;
  