import {
  Page,
  Card,
  Tooltip,
  LegacyStack,
  InlineStack,
  Layout,
  Banner,
  BlockStack,
  Text,
  Button,
  CalloutCard,
  Icon,
  ProgressBar,
  Badge,
  InlineGrid,
  SkeletonBodyText,
  Box,
  LegacyCard,
  Collapsible,
  RadioButton,
  Select,
} from "@shopify/polaris";
import Joyride, { ACTIONS, EVENTS, STATUS } from "react-joyride";

import {
  AlertCircleIcon,
  ArrowRightIcon,
  StatusActiveIcon,
  StoreIcon,
  XCircleIcon,
} from "@shopify/polaris-icons";
import { useLoaderData,useNavigate } from "@remix-run/react";
import { useEffect, useState,useCallback } from "react";
import { authenticate } from "../shopify.server";
import { TbExternalLink } from "react-icons/tb";
import upgradePremium from "./assets/upgradePremium.jpg";
import prisma from "../db.server";
import { json } from "@remix-run/node";
import axios from "axios";
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
export const loader = async ({ request }) => {
  const { session } = await authenticate.admin(request);
  console.log(session);
  let user = await prisma.users.findFirst({
    where: {
      shopurl: session.shop,
    },
  });
  if (!user) {
  await sleep(2000);
     user = await prisma.users.findFirst({
    where: {
      shopurl: session.shop,
    },
  });
    
  }
  console.log(user);
  const user_id = user?.id;
  console.log("userId: ", user_id);
  console.log("user plan :", user.plan);

  const amz_keys = await prisma.amz_keys.findFirst({
    where: {
      user_id: user_id,
    },
  });
    const amzRequest = await prisma.amz_reportrequests.findFirst({
    where: {
      user_id: user_id,
    },
    orderBy: {
      id: "desc",
    },
  });

  console.log("keys : ", amz_keys);
  return json({ user, amz_keys, amzRequest });
};

export default function Index() {
  const { user, amz_keys, amzRequest } = useLoaderData();
  const navigate = useNavigate();

  const marketplaceList = [
    { id: "A2Q3Y263D00KWC", country: "BR" },
    { id: "A2EUQ1WTGCTBG2", country: "CA" },
    { id: "A1AM78C64UM0Y8", country: "MX" },
    { id: "ATVPDKIKX0DER", country: "US" },
    { id: "A2VIGQ35RCS4UG", country: "AE" },
    { id: "A1PA6795UKMFR9", country: "DE" },
    { id: "ARBP9OOSHTCHU", country: "EG" },
    { id: "A1RKKUPIHCS9HS", country: "ES" },
    { id: "A13V1IB3VIYZZH", country: "FR" },
    { id: "AMEN7PMS3EDWL", country: "BE" },
    { id: "A1F83G8C2ARO7P", country: "UK" },
    { id: "A21TJRUUN4KGV", country: "IN" },
    { id: "APJ6JRA9NG5V4", country: "IT" },
    { id: "A1805IZSGTT6HS", country: "NL" },
    { id: "A1C3SOZRARQ6R3", country: "PL" },
    { id: "A17E79C6D8DWNP", country: "SA" },
    { id: "A2NODRKZP88ZB9", country: "SE" },
    { id: "A33AVAJ2PDY3EV", country: "TR" },
    { id: "A28R8C7NBKEWEA", country: "IE" },
    { id: "A1VC38T7YXB528", country: "JP" },
    { id: "A19VAU5U5O7RUS", country: "SG" },
    { id: "A39IBJ37TRP1C6", country: "AU" },
  ];
  const marketplace = [
    { key: "ATVPDKIKX0DER", value: "amazon.com" },
    { key: "A2EUQ1WTGCTBG2", value: "amazon.ca" },
    { key: "A1AM78C64UM0Y8", value: "amazon.com.mx" },
    { key: "A1F83G8C2ARO7P", value: "amazon.co.uk" },
    { key: "A21TJRUUN4KGV", value: "amazon.in" },
    { key: "A1PA6795UKMFR9", value: "amazon.de" },
    { key: "A1RKKUPIHCS9HS", value: "amazon.es" },
    { key: "A13V1IB3VIYZZH", value: "amazon.fr" },
    { key: "APJ6JRA9NG5V4", value: "amazon.it" },
    { key: "ARBP9OOSHTCHU", value: "amazon.eg" },
    { key: "A2VIGQ35RCS4UG", value: "amazon.ae" },
  ];
  const marketplaceName =
    marketplaceList.find((m) => m.id === amz_keys?.marketplace_id)?.country ||
    "Unknown Marketplace";
  const [welcome_tour, setWelcomeTour] = useState(user.welcome_tour ?? false);

  const [loading, setLoading] = useState(true);
  const [counts, setCounts] = useState(null);
  const [pending_request, setPendingRequest] = useState(amzRequest?.status === 'pending' ? 1 : 0);

  useEffect(() => {
    if (user) {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    

    if (user?.id) fetchCounts();
  }, [user]);
  async function fetchCounts() {
    const res = await fetch(`/api/productCount?user_id=${user.id}`);
    const data = await res.json();
    setCounts(data.countsByStatus);
  }
     useEffect(() => {
    let timeoutId;
    const fetchRequest = async () => {
      if (pending_request === 1) {
        console.log("ssssssssssssssssssssssssskkkkkkkdk");
        try {
          const response = await axios.get("/api/fetchProductCount", {
            params: {
              userId: user.id,
            },
          });
   
          
          if (
            response.data?.amzRequest != null &&
            response.data?.amzRequest?.status == "readyforshopify"
          ) {
            console.log("444444444444444444");
            clearTimeout(timeoutId);
            setPendingRequest(0);
            return;
          }
          setCounts(response.data.countsByStatus);
          timeoutId = setTimeout(fetchRequest, 5000);
        } catch (error) {
          console.log(error);
        }
      }
    };

    fetchRequest();
    return () => clearTimeout(timeoutId);
  }, []);
    const handleJoyrideCallback = useCallback(async (data) => {
      const { status, type } = data;
      const finishedStatuses = [STATUS.FINISHED, STATUS.SKIPPED];
  
      if (finishedStatuses.includes(status)) {
        try {
          console.log("sdfsdfsdfsdfs");
          const response = await axios.get("/api/welcomeTour", {
            params: {
              userId: user.id,
            },
          });
          console.log(response);
        } catch (e) {
          console.log(e);
        }
      }
  
    }, []);

  console.log("user plan :", user.plan);
  console.log("user membership :", user.membershiptype);

  const planMapping = {
    0: { type: "Free", cycle: "-" },
    1: { type: "Premium - Bronze", cycle: "Monthly" },
    2: { type: "Premium - Silver", cycle: "Monthly" },
    3: { type: "Premium - Gold", cycle: "Monthly" },
    4: { type: "Premium - Bronze", cycle: "Yearly" },
    5: { type: "Premium - Silver", cycle: "Yearly" },
    6: { type: "Premium - Gold", cycle: "Yearly" },
    7: { type: "Premium - custom", cycle: "Yearly" },
  };
  
  const userPlan = user.plan;
  const billingPlan = planMapping[userPlan] || planMapping[0];
  const membershipType = user.membershiptype ?? "free";
   const [steps] = useState([
      {
        target: ".tour-header",
        content: "Start the tour.",
        placement: "bottom",
      },
      {
        target: ".amazon-product",
        content:
          "Here is the number of your amazon products , you can go to the amazon products page by clicking on this card .",
        placement: "right",
      },
      {
        target: ".ready-to-import-product",
        content:
          "Here is the total number of products ready to import.",
        placement: "top",
      },
      {
        target: ".import-product",
        content: "Here is the total number of imported products from this app.",
        placement: "left",
      },
      {
        target: ".plan",
        content: "This is your plan details.",
        placement: "top",
      },
      {
        target: ".Aaccount",
        content: "This is your Amazon account details.",
        placement: "top",
      },
      {
        target: ".account_status",
        content: "This is your account status.",
        placement: "top",
      },
      {
        target: "body",
        placement: "center",
        content: (
          <div style={{ textAlign: "center" }}>
            <strong>🎉 Tour complete!</strong>
            <div className="mt-2 text-sm">Thanks for taking the tour.</div>
          </div>
        ),
      },
    ]);

  const amazonProducts = counts?.all ?? 0;
  const shopifyProducts = counts?.ready_to_import ?? 0;
  const importedProducts = counts?.imported ?? 0;
  const skuLimit = user.skulimit ?? 5;
  const importConsumed = user.skuconsumed ?? 0;
  const [setupStep, setSetupStep] = useState(user.setup_step ?? "first");
  const [progressBarText, setProgressBarText] = useState(
    user.setup_step === "first"
      ? "0 of 2 Task completed"
      : "1 of 2 Task completed",
  );
  const [progressBarValue, setProgressBarValue] = useState(
    user.setup_step === "first" ? 0 : 50,
  );
  const [selectedOption, setSelectedOption] = useState("syncBoth");
  const [marketplaceId, setMarketplaceId] = useState("ATVPDKIKX0DER");
  // Active step for collapsible
  const [activeStep, setActiveStep] = useState(
    user.setup_step === "first" ? 1 : 2,
  );
  let content;
    const handleSettingSave = async () => {
    try {
      const response = await axios.post("/api/setupSetting", {
        data: [selectedOption],
        userId: user.id,
      });
      if (response.data?.msg) {
        window.location.reload();
        // shopify.toast.show(response.data?.msg);
        setSetupStep("Done");
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleAccount = () => {
    // Logic to handle account connection
    console.log("Connecting account with marketplace ID:", marketplaceId);
    // After successful connection, update setup step
    setSetupStep("second");
    const authUrl = `https://shopify.infoshore.biz/xpert/authorize.php?key=${user.id}&marketplace_id=${marketplaceId}`;
    // break out of iframe
    window.open(authUrl, "_top");
  }

  if (user.setup_step == "Done") {
    content = (
      <>
       <Joyride
          steps={steps}
          run={!welcome_tour}
          continuous={true}
          showSkipButton={true}
          showProgress={true}
          disableScrolling={false}
          styles={{
            options: {
              zIndex: 10000,
              primaryColor: "#FF9900",
              borderRadius: 8,
            },
            tooltip: {
              width: "280px",
              maxWidth: "280px",
              fontSize: "14px",
              lineHeight: "1.4",
            },
            buttonNext: {
              backgroundColor: "#FF9900	",
              fontSize: "12px",
            },
            buttonBack: {
              color: "#FF9900",
              fontSize: "12px",
            },
          }}
          callback={handleJoyrideCallback}
        />
        <Page fullWidth>
     
             {user.plan === 0 && user.skuconsumed < 5 && amzRequest?.status != 'readyforshopify' && (
                      <div style={{ marginBottom: 20 }}>
                        <Banner>
                          <p>
                            We are fetching Amazon listings from your Amazon seller
                            account. Please{" "}
                            <Button
                              variant="plain"
                              onClick={() => navigate("/app/products")}
                            >
                              Click here{" "}
                            </Button>{" "}
                            to view and import 5 FREE products.
                          </p>
                        </Banner>
                      </div>
                    )}
                   
                    {user.plan > 1 &&  amzRequest?.status != 'readyforshopify' && (
                      <div style={{ marginBottom: 20 }}>
                        <Banner>
                          <p>
                            We are fetching Amazon listings from your Amazon seller
                            account. Please{" "}
                            <Button
                              variant="plain"
                              onClick={() => navigate("/app/products")}
                            >
                              Click here{" "}
                            </Button>{" "}
                            to view and import products.
                          </p>
                        </Banner>
                      </div>
                    )}
                    {amzRequest?.status == 'readyforshopify' && user.skuconsumed < user.skulimit && (
          
                      <div style={{ marginBottom: 20 }}>
                        <Banner
                        >
                          <Text as="p" fontWeight="medium">
                            All your Amazon products are fetched and ready —{" "}
                            <Button
                              variant="plain"
                              onClick={() => navigate("/app/products")}
                            >
                              click here{" "}
                            </Button>{" "}
                            to import them into your Shopify store.{" "}
                          </Text>
                        </Banner>
                      </div>
                    )}
                     <div className="banner">
                        {  user.skuconsumed >= user.skulimit ? (
                          <>
                            <Banner tone="critical">
                              Please upgrade your plan to continue importing items.
                              <Button onClick={() => navigate("/app/plan")}>
                                Upgrade Plan
                              </Button>
                            </Banner>
                          </>
                        ) : (
                          <></>
                        )}
                      </div>
          
          <div style={{ marginBottom: "20px" }}>
            <Card sectioned>
              <InlineStack gap={300} blockAlign="center" align="space-evenly">
                <div className="amazon-product hover-card">
                  {loading ? (
                    <Card sectioned>
                      <SkeletonBodyText lines={4} />
                    </Card>
                  ) : (
                    <Card sectioned>
                      <p className="heading_title">
                        Amazon Products
                        <TbExternalLink />
                      </p>
                      <br />
                      <Tooltip
                        preferredPosition="below"
                        content="Here is a comprehensive list of your active amazon listings."
                      >
                        <h1 className="heading_text">{amazonProducts} </h1>
                      </Tooltip>
                    </Card>
                  )}
                </div>
                {/* Ready To Import*/}
                <div className="ready-to-import-product hover-card">
                  {loading ? (
                    <Card sectioned>
                      <SkeletonBodyText lines={4} />
                    </Card>
                  ) : (
                    <Card sectioned>
                      <p className="heading_title">Ready To Import</p>
                      <br />
                      <Tooltip
                        preferredPosition="below"
                        content="This indicates the total number of products available on your Shopify store."
                      >
                        <h1 className="heading_text">{shopifyProducts}</h1>
                      </Tooltip>
                    </Card>
                  )}
                </div>
                {/* Imported Products */}
                <div className="import-product hover-card">
                  {loading ? (
                    <Card sectioned>
                      <SkeletonBodyText lines={4} />
                    </Card>
                  ) : (
                    <Card sectioned>
                      <p className="heading_title">Imported Products</p>
                      <br />
                      <Tooltip
                        preferredPosition="below"
                        content="This is the quantity of products you've successfully imported on Amazon or Shopify through this application."
                      >
                        <h1 className="heading_text">{importedProducts}</h1>
                      </Tooltip>
                    </Card>
                  )}
                </div>
              </InlineStack>
            </Card>
          </div>
          <Layout>
            <Layout.Section variant="oneThird">
              <div style={{ marginBottom: "20px" }} className="plan">
                {loading ? (
                  <Card roundedAbove="md">
                    <SkeletonBodyText lines={4} />
                  </Card>
                ) : (
                  <Card>
                    <BlockStack gap="200">
                      <Text as="h2" variant="headingMd">
                        Plan
                      </Text>
                      <Banner
                        tone={membershipType === "free" ? "info" : "success"}
                        title={
                          membershipType === "free" ? "Free Plan" : "Paid Plan"
                        }
                      />
                      <BlockStack gap="200">
                        {[
                          {
                            label: "Pricing",
                            value:
                              membershipType === "free"
                                ? "$0/month"
                                : billingPlan.cycle,
                          },
                          { label: "Import Credit", value: skuLimit },
                          { label: "Import Consumed", value: importConsumed },
                        ].map((item, index) => (
                          <InlineStack key={index} align="space-between">
                            <Text variant="bodyMd">{item.label}</Text>
                            <Text variant="bodyMd">{item.value}</Text>
                          </InlineStack>
                        ))}
                      </BlockStack>
                    </BlockStack>
                  </Card>
                )}
              </div>
              {loading ? (
                <Card roundedAbove="md">
                  <SkeletonBodyText lines={4} />
                </Card>
              ) : (
                <div className="Aaccount"> 
                <Card>
                  <BlockStack gap="200">
                    <Text as="h2" variant="headingMd">
                      Amazon Account
                    </Text>
                    <BlockStack gap="200">
                      <InlineStack align="space-between">
                        <Text variant="bodyMd">Merchant ID</Text>
                        {/* <Text variant="bodyMd">A1PA6795UKMFR9</Text> */}
                        {console.log(amz_keys)
                        }
                        <Badge>{amz_keys?.merchant_id}</Badge>
                      </InlineStack>
                      <InlineStack align="space-between">
                        <Text variant="bodyMd">Status</Text>
                        <Badge
                          tone={
                            amz_keys?.valid === true ? "success" : "critical"
                          }
                        >
                          {amz_keys?.valid === true ? "Active" : "InActive"}
                        </Badge>
                      </InlineStack>
                      <InlineStack align="space-between">
                        <Text variant="bodyMd">Site</Text>
                        <Text>{marketplaceName}</Text>
                      </InlineStack>
                    </BlockStack>
                  </BlockStack>
                </Card>
                </div>

              )}
            </Layout.Section>

            <Layout.Section>
               <div className="account_status">

              {loading ? (
                <Card sectioned>
                  <SkeletonBodyText lines={10} />
                </Card>
              ) : (
                <>
                  {membershipType === "paid" ? (
                    <Card>
                      <BlockStack gap="300">
                        <InlineStack align="space-between">
                          <Text as="h2" variant="headingMd">
                            Account Status
                          </Text>
                          <Badge tone="info">Premium</Badge>
                        </InlineStack>

                        <ProgressBar
                          progress={100}
                          tone="success"
                          size="small"
                        />

                        <InlineGrid gap="300" columns={2}>
                          <Card sectioned background="bg-surface-secondary">
                            <BlockStack gap="200">
                              <Text variant="headingMd">Your Subscription</Text>

                              <InlineStack align="space-between">
                                <Text>Plan Type</Text>
                                <Text fontWeight="bold">
                                  {billingPlan.type}
                                </Text>
                              </InlineStack>

                              <InlineStack align="space-between">
                                <Text>Billing Cycle</Text>
                                <Text fontWeight="bold">
                                  {billingPlan.cycle}
                                </Text>
                              </InlineStack>
                            </BlockStack>
                          </Card>

                          <Card sectioned background="bg-surface-secondary">
                            <BlockStack gap="200">
                              <Text variant="headingMd">Usage Statistics</Text>

                              <InlineStack align="space-between">
                                <Text>Products Imported</Text>
                                <Text fontWeight="bold">
                                  {importedProducts} of {skuLimit}
                                </Text>
                              </InlineStack>

                              <InlineStack align="space-between">
                                <Text>Remaining Products</Text>
                                <Text fontWeight="bold">
                                  {skuLimit - importedProducts}
                                </Text>
                              </InlineStack>
                            </BlockStack>
                          </Card>
                        </InlineGrid>

                        {/* CALLOUT CARD */}
                        <div>
                          <InlineStack align="center">
                            <CalloutCard
                              title="Want to Get the Most Out of Your Premium Features?"
                              illustration={upgradePremium}
                              primaryAction={{
                                content: "Book Now",
                                url: "https://calendly.com/madhu-infoshore/30min?month=2025-05",
                                target: "_blank",
                              }}
                            >
                              <Text as="p">
                                📅 Book a personalized strategy session to
                                unlock the full potential of premium tools and
                                features of your plan!
                              </Text>
                            </CalloutCard>
                          </InlineStack>
                        </div>
                      </BlockStack>
                    </Card>
                  ) : (
                    <Card>
                      <BlockStack gap="200">
                        <Text as="h2" variant="headingMd">
                          Account Status
                        </Text>
                        <ProgressBar
                          progress={66}
                          tone="success"
                          size="small"
                        />
                        <InlineStack blockAlign="center" gap="300">
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <Icon source={StatusActiveIcon} tone="success" />
                          </div>
                          <Text variant="bodyMd">
                            Connect your amazon or Shopify store
                          </Text>
                        </InlineStack>
                        <InlineStack blockAlign="center" gap="300">
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <Icon source={StatusActiveIcon} tone="success" />
                          </div>
                          <Text variant="bodyMd">Complete account setup</Text>
                        </InlineStack>
                        <InlineStack blockAlign="center" gap="300">
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <Icon source={XCircleIcon} tone="critical" />
                          </div>
                          {importedProducts === 0 ? (
                            <Button variant="plain" url="/app/products">
                              <div style={{ color: "black" }}>
                                Import your first product
                              </div>
                            </Button>
                          ) : (
                            <Button variant="plain">
                              <div style={{ color: "black" }}>
                                Upgrade to a Premium Plan
                              </div>
                            </Button>
                          )}
                        </InlineStack>

                        <div style={{ marginTop: "6%" }}>
                          <InlineStack gap="400" align="center">
                            <CalloutCard
                              title="Supercharge Your Store with Premium"
                              illustration="https://cp.infoshoreapps.com/api/public/uploads/image.png"
                              primaryAction={{
                                content: "Upgrade to Premium",
                              }}
                            >
                              <Text as="p">
                                🚀 Import more products, unlock powerful
                                analytics, and get 24/7 support to grow your
                                business faster.
                              </Text>
                            </CalloutCard>
                          </InlineStack>
                        </div>
                      </BlockStack>
                    </Card>
                  )}
                </>
              )}
               </div>
            </Layout.Section>
          </Layout>
          <p style={{ textAlign: "center", marginTop: "20px", color: "#666" }}>
            Copyright 2022 InfoShore Technology Solutions LLP. All rights
            reserved.
          </p>
        </Page>

        <style>
          {`
        .hover-card {
          transition: transform 0.3s ease, box-shadow 0.3s ease;
          min-width: 190px;
          width: min-content;
          flex-grow: 1;
          cursor: pointer;
          border-radius: 15px;
        }
        .hover-card:hover{
           transform: translateY(-10px);
           box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
           border-radius: 15px;
        }
        .heading_text{
          text-align: center;
          font-size: 25px;
          font-weight: bold;
          color: #4e5358;
        }
        .heading_title{
          font-size: 15px;
          font-weight: 550;
          cursor: pointer;
          padding: 0%;
          text-align: center;
          color: #5f729c;
        }
        `}
        </style>
      </>
    );
  } else {
    content = (
      <>
        {/* Header */}
        <Box paddingBlockEnd="4">
          <Text variant="headingXl" as="h1" alignment="center">
            PRO Importer For Amazon
          </Text>
          <Text variant="bodyMd" as="p" alignment="center" tone="subdued">
            Set up your Amazon account to start importing products
          </Text>
        </Box>
        <Page>
          <Box>
            <Card>
              {/* Progress bar */}
              <div style={{ padding: "16px" }}>
                {/* Header row */}
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    width: "100%",
                    marginBottom: "8px",
                  }}
                >
                  {/* Left side */}
                  <Text as="span" variant="bodyMd" fontWeight="bold">
                    {progressBarText}
                  </Text>

                  {/* Right side */}
                </div>

                {/* Progress bar */}
                <ProgressBar
                  progress={progressBarValue}
                  tone="highlight"
                  size="small"
                />
              </div>

              {/* Setup Steps */}
              <div style={{ margin: "30px" }}>
                <BlockStack gap="400">
                  {/* STEP 1 */}
                  <LegacyStack vertical>
                    <Button
                      // onClick={() => toggleStep(1)}
                      // ariaExpanded={activeStep === 1}
                      ariaControls="step-1"
                      variant="tertiary"
                      fullWidth
                      textAlign="left"
                      disabled={setupStep == "second"}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "8px",
                        }}
                      >
                        <Icon
                          source={
                            user.setup_step === "first"
                              ? AlertCircleIcon
                              : StatusActiveIcon
                          }
                          tone="success"
                        />
                        <Text as="h2" variant="headingMd" style={{ margin: 0 }}>
                          Step 1: Connect your Amazon account
                        </Text>
                      </div>
                    </Button>
                    <div style={{ marginLeft: "20px" }}>
                      <Collapsible
                        open={activeStep === 1}
                        id="step-1"
                        transition={{
                          duration: "200ms",
                          timingFunction: "ease-in-out",
                        }}
                        expandOnPrint
                      >
                        <Tooltip
                          content="Click here to connect your amazon account."
                          preferredPosition="below"
                        >
                          <Select 
                            label="Select Marketplace"
                            options={marketplace.map((m) => ({
                              label: m.value,
                              value: m.key,
                            }))}
                            value={
                              marketplaceId 
                            }
                            onChange={(value) => {
                              setMarketplaceId(value);
                            }
                          }
                          />
                          <br />
                          <Button
                            icon={StoreIcon}
                            variant="primary"
                            onClick={() => {
                              handleAccount();
                                setProgressBarValue(50);
                                setProgressBarText("1 of 2 Task completed");
                            }}
                          >
                            Connect Amazon Shop
                          </Button>
                        </Tooltip>
                      </Collapsible>
                    </div>
                  </LegacyStack>

                  {/* STEP 2 */}
                  <LegacyStack vertical>
                    <Button
                      // onClick={() => toggleStep(2)}
                      // ariaExpanded={activeStep === 2}
                      ariaControls="step-2"
                      variant="tertiary"
                      fullWidth
                      textAlign="left"
                      disabled={setupStep != "second"}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "8px",
                        }}
                      >
                        <Icon source={AlertCircleIcon} tone="success" />
                        <Text as="h2" variant="headingMd" style={{ margin: 0 }}>
                          Step 2: Inventory Sync Setting
                        </Text>
                      </div>
                    </Button>
                    <div style={{ marginLeft: "20px" }}>
                      <Collapsible
                        open={activeStep === 2}
                        id="step-2"
                        transition={{
                          duration: "200ms",
                          timingFunction: "ease-in-out",
                        }}
                        expandOnPrint
                      >
                        <>
                          <Text as="p">
                            Select the appropriate order and inventory sync
                            option for your Shopify and Amazon store
                          </Text>
                          {/* Use RadioButtons instead of checkboxes */}
                          <BlockStack gap="200">
                            <RadioButton
                              label="Enable both Inventory & Price sync"
                              checked={selectedOption === "syncBoth"}
                              id="syncBoth"
                              name="syncOption"
                              onChange={() => setSelectedOption("syncBoth")}
                            />
                            <RadioButton
                              label="Enable Inventory sync only"
                              checked={selectedOption === "inventoryOnly"}
                              id="inventoryOnly"
                              name="syncOption"
                              onChange={() =>
                                setSelectedOption("inventoryOnly")
                              }
                            />
                            <RadioButton
                              label="Enable Price sync only"
                              checked={selectedOption === "priceOnly"}
                              id="priceOnly"
                              name="syncOption"
                              onChange={() => setSelectedOption("priceOnly")}
                            />
                            <RadioButton
                              label="None"
                              checked={selectedOption === "none"}
                              id="none"
                              name="syncOption"
                              onChange={() => setSelectedOption("none")}
                            />
                          </BlockStack>
                          {/* <div style={{ marginTop: "20px", float: "right" }}> */}
                          <Tooltip
                            content="click here to complete setup."
                            preferredPosition="below"
                          >
                            <Button
                              variant="primary"
                              onClick={handleSettingSave}
                              className="flex items-center gap-2"
                              fullWidth
                              icon={ArrowRightIcon}
                            >
                              <div
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  gap: "8px",
                                }}
                              >
                                Complete
                                <ArrowRightIcon />
                              </div>
                            </Button>
                          </Tooltip>
                          {/* </div> */}
                        </>
                      </Collapsible>
                    </div>
                  </LegacyStack>
                </BlockStack>
              </div>
            </Card>
          </Box>
        </Page>
      </>
    );
  }

  return <>{content}</>;
}
