import {
  LegacyCard,
  Page,
  Tabs,
  IndexTable,
  TextContainer,
  Text,
  Button,
  Badge,
  useIndexResourceState,
  Modal,
  Banner,
  Pagination,
  Select,
  IndexFilters,
  useSetIndexFiltersMode,
  Tooltip,
  Link,
  Card,
  EmptyState,
  SkeletonBodyText,
} from "@shopify/polaris";
import { useState, useEffect } from "react";
import { ImportIcon } from "@shopify/polaris-icons";
import { useLoaderData, useLocation, useNavigate } from "@remix-run/react";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";
import { json } from "@remix-run/node";
import styles from "../styles/app.products.module.css";
import axios from "axios";
import wrap from "word-wrap";
import IsMobile from "./common/isMobile";
import { FcPicture } from "react-icons/fc";
import { BiLogoEtsy } from "react-icons/bi";
import { FaShopify } from "react-icons/fa";

export const loader = async ({ request }) => {
  const { session } = await authenticate.admin(request);

  const user = await prisma.users.findFirst({
    where: { shopurl: session.shop },
  });

  const user_id = user?.id;

  const amzKey = await prisma.amz_keys.findFirst({
    where: { user_id },
    select: { marketplace_id: true },
  });

  const marketplaceId = amzKey?.marketplace_id ?? null;
  return json({ user, marketplaceId });
};

export default function Products() {
  let { user } = useLoaderData();
  const navigate = useNavigate();

  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedTab, setSelectedTab] = useState(0);
  const [counts, setCounts] = useState({});
  const [perPageValue, setPerPageValue] = useState("20");
  const [current_page, setCurrentPage] = useState(1);
  const [productData, setproductData] = useState(false);
  const [firstProductNo, setFirstProductNo] = useState(1);
  const [lastProductNo, setLastProductNo] = useState("20");
  const [status, setStatus] = useState("All");
  const userId = user?.id;
  const [totalItems, setTotalItems] = useState(0);
  const [totalProduct, setTotalProduct] = useState(0);
  const isMobile = IsMobile();
  const [orderBy, setOrderBy] = useState("Product desc");
  const [activeModal, setActiveModal] = useState(false);
  const [variants, setvariants] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [pagination, setPagination] = useState({ total: 0, totalPages: 1 });
  const [sortSelected, setSortSelected] = useState(["Product desc"]);
  const [queryValue, setQueryValue] = useState("");
  const [upgradeModalActive, setUpgradeModalActive] = useState(false);
  const toggleUpgradeModal = () => setUpgradeModalActive((prev) => !prev);
  const selectable = user.plan > 0 ? true : false;
  const [selectImportIds, setSelectedImport] = useState([]);

  const [countOfProduct, setCountOfProduct] = useState({
    all: 0,
    already_exist: 0,
    ready_to_import: 0,
    import_in_progress: 0,
    imported: 0,
    error: 0,
    linked: 0,
  });
  const [query, setQuery] = useState("");
  const { mode, setMode } = useSetIndexFiltersMode();
      const {
    selectedResources,
    allResourcesSelected,
    handleSelectionChange,
    removeSelectedResources,
  } = useIndexResourceState(products);

  const sortOptions = [
    { label: "Product", value: "Product asc", directionLabel: "Ascending" },
    { label: "Product", value: "Product desc", directionLabel: "Descending" },
    { label: "Title", value: "Title asc", directionLabel: "Title asc" },
    { label: "Title", value: "Title desc", directionLabel: "Title desc" },
  ];

  const headerStyle = {
    padding: "10px 14px",
    textAlign: "left",
    fontWeight: 600,
    fontSize: "14px",
    color: "#202223",
    borderBottom: "1px solid #dfe3e8",
  };
  const cellStyle = {
    padding: "10px 14px",
    textAlign: "left",
    fontSize: "14px",
    color: "#3c3f41",
    borderBottom: "1px solid #dfe3e8",
    backgroundColor: "#fff",
  };

  const statusKeyMap = {
    All: "all",
    "Already Exist": "already_exist",
    "Ready To Import": "ready_to_import",
    "Import In Progress": "import_in_progress",
    Imported: "imported",
    Error: "error",
    Linked: "linked",
  };
  const [itemProducts, setItemProducts] = useState([
    `All`,
    `Ready To Import`,
    "Imported",
    "Import In Progress",
    "Already Exist",
  ]);

  const tabs = itemProducts.map((item, index) => {
    const key = statusKeyMap[item];
    const badgeValue = key ? (countOfProduct[key] ?? 0) : 0;

    return {
      content: item,
      badge: badgeValue,
      index,
      onAction: () => {},
      id: `${item}-${index}`,
      isLocked: index === 0,
      actions: index === 0 ? [] : [],
    };
  });
  const handlePerPage = (event) => {
    setCurrentPage(1);
    setPerPageValue(event.target.value);
    setLastProductNo(event.target.value);
    fetchproduct(status, query, orderBy, event.target.value);
    //console.log(event.target.value);
  };

  const getBadgeTone = (status) => {
    switch (status.toLowerCase()) {
      case "ready to import":
        return "info";
      case "import in progress":
      case "reimport in progress":
        return "warning";
      case "imported":
        return "success";
      case "already exist":
        return "attention";
      case "error":
        return "critical";
      case "block":
        return "warning";
      default:
        return "attention";
    }
  };
  const promotedBulkActions = [
    {
      content: `Import Selected ${selectImportIds.length} Products`,
      onAction: () => {
        handleImportRequest(selectImportIds);
      },
    },
    ...(user.plan > 0
      ? [
          {
            title: "Action",
            actions: [
              {
                icon: ImportIcon,
                content: "Import Selected Product",
                onAction: () => handleImportRequest(selectImportIds),
              },
             {
                icon: ImportIcon,
                content: "Import All Products",
                onAction: () => handleAllImportRequest(),
              },
            ],
          },
        ]
      : []),
  ];
  const handleFetchShopifyProductCount = async () => {
    try {
      const response = await axios.get("/api/productCount", {
        params: {
          user_id: user.id,
        },
      });
      console.log("handleFetchShopifyProductCount ", response);
      if (response.data.countsByStatus) {
        setCountOfProduct(response.data.countsByStatus);
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    fetchproduct("All");
  }, [user]);

  const reverseStatusMap = {
    Already_Exist: "Already Exist",
    Ready_to_Import: "Ready to Import",
    Import_in_progress: "Import in progress",
    Imported: "Imported",
    error: "error",
    linked: "Linked",
  };
  const fetchproduct = async (
    status,
    query,
    orderBy,
    parPage = perPageValue,
    page = current_page,
  ) => {
    try {
      setproductData(false);
      setStatus(status);
      let lastpage = ((current_page * page) / current_page) * parPage;
      setLastProductNo(lastpage);
      setFirstProductNo(lastpage - parPage + 1);
      // handleFetchShopifyProductCount();
      const res = await axios.get(`/api/products/`, {
        params: {
          status: status,
          user_id: userId,
          query: query,
          orderBy: orderBy,
          parPage: parPage,
          page: page,
        },
      });
      console.log("res.data -> ", res);
      handleFetchShopifyProductCount();
      const productData = res.data.productsWithData;
      setproductData(true);
      setTotalProduct(res.data.totalProduct);
      setTotalItems(res.data.totalCount);
      if (lastProductNo > res.data.totalCount) {
        setLastProductNo(res.data.totalCount);
      }
      const formattedProducts = productData.map((product) => {
        console.log(product);

        let firstImage = "";
        try {
          firstImage = product.firstImage.split("|")[0] ?? "";

          // firstImage = images?.image_url || "";
        } catch (e) {
          console.error(
            "Invalid JSON in product_image_data:",
            product.product_image_data,
          );
        }
        console.log("product.status ->>> ", product.status);
        console.log(reverseStatusMap[product.status]);
        console.log("product?.block ->>> ", product?.block);

        return {
          id: product.product_id,
          title: wrap(product.title, { width: 70 }),
          status: reverseStatusMap[product.status],
          block: product?.block || 0,
          has_variation: product.has_variation || 0,
          shopifyproductid: product.shopifyproductid || 0,
          image: firstImage,
          variants: product.variant || [],
          variantCount: product.variant ? product.variant.length : 0,
        };
      });
      setProducts(formattedProducts);
    } catch (error) {
      console.log("error while fetching products :: ", error);
    }
  };
  const handleblockproduct = async (productId) => {
    console.log("productId ->>> ", productId);
    let productIdArray = Array.isArray(productId) ? productId : [productId];
    if (productIdArray.length === 0) {
      console.error("No valid product IDs provided");
      return;
    }
    try {
      const response = await axios.get(`/api/blockProduct`, {
        params: {
          userId: user.id,
          productId: productIdArray.join(","),
        },
      });
      console.log("response ->>> ", response);
      shopify.toast.show("Product blocked successfully");
      fetchproduct(status, query, orderBy, perPageValue, current_page);
    } catch (error) {
      console.error("Error blocking product:", error);
    }
  };
  const fetchAmazonProducts = async () => {
    try {
      const response = await axios.get(`/api/fetchAmazonProducts`, {
        params: {
          userId: user.id,
        },
      });
      console.log("Amazon products fetched:", response.data);
      if (response.data.msg) {
        shopify.toast.show(response.data.msg);
      }
      // fetchproduct(status, query, orderBy, perPageValue, current_page);
    } catch (error) {
      console.error("Error fetching Amazon products:", error);
    }
  };
  const handleunblockproduct = async (productId) => {
    console.log("productId ->>> ", productId);
    let productIdArray = Array.isArray(productId) ? productId : [productId];
    if (productIdArray.length === 0) {
      console.error("No valid product IDs provided");
      return;
    }
    try {
      const response = await axios.get(`/api/unblockproduct`, {
        params: {
          userId: user.id,
          productId: productIdArray.join(","),
        },
      });
      console.log("response ->>> ", response);
      shopify.toast.show("Product unblocked successfully");
      fetchproduct(status, query, orderBy, perPageValue, current_page);
    } catch (error) {
      console.error("Error unblocking product:", error);
    }
  };

  const handleFiltersQueryChange = (value) => {
    console.log(value);
    setQuery(value);
    setQueryValue(value);
    fetchproduct(status, value);
  };

  const handleImportRequest = async (productId) => {
    console.log("productId ->>> ", productId);
    let productIdArray = Array.isArray(productId) ? productId : [productId];
    if (productIdArray.length === 0) {
      console.error("No valid product IDs provided");
      return;
    }

    console.log(user.skuconsumed);
    console.log(user.skulimit);

    if (user.skuconsumed + productIdArray.length > user.skulimit) {
      toggleUpgradeModal();
      return;
    }
      user.skuconsumed = productIdArray.length + user.skuconsumed;

    try {
      if (user.plan === 0) {
        setProducts((prevProducts) =>
          prevProducts.map((product) =>
            productIdArray.includes(product.id)
              ? { ...product, status: "Import in progress" }
              : product
          )
        );
        // const response = await axios.get(
        //   `https://shopify.infoshore.biz/xpert/cronjobs/importtoshopifytrail.php`,
        //   {
        //     params: {
        //       user_id: user.id,
        //       product_id: productIdArray.join(","),
        //     },
        //   },
        // );
        const params = new URLSearchParams({
          user_id: user.id,
          product_id: productIdArray.join(","),
        });

        const response = await fetch(
          `https://shopify.infoshore.biz/xpert/cronjobs/importtoshopifytrail.php?${params.toString()}`,
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        const data = await response.json();

        // user.skuconsumed = productIdArray.length + user.skuconsumed;
        setProducts([]);
        fetchproduct(status, query, orderBy, perPageValue, current_page);

        console.log("response ->>> ", data);
      } else {
        setProducts((prevProducts) =>
          prevProducts.map((product) =>
            productIdArray.includes(product.id)
              ? { ...product, status: "Import in progress" }
              : product
          )
        );
        const response = await axios.get(`/api/push`, {
          params: {
            userId: user.id,
            productId: productIdArray.join(","),
          },
        });
        console.log("response ->>> ", response);
        user.skuconsumed += productIdArray.length;
        removeSelectedResources(selectedResources);
        console.log(response.data);
        
        if (response.data.message) {
          shopify.toast.show(response.data.message);
        }

        fetchproduct(status, query, orderBy, perPageValue, current_page);
      }
    } catch (error) {
        setProducts([]);

        fetchproduct(status, query, orderBy, perPageValue, current_page);

      console.error("Error sending import request:", error);
    }
  };
    const handleAllImportRequest = async () => {

    console.log(user.skuconsumed);
    console.log(user.skulimit);

  
    try {
    
        const response = await axios.get(`/api/pushall`, {
          params: {
            userId: user.id,
          },
        });
        console.log("response ->>> ", response);
        removeSelectedResources(selectedResources);

        if (response.data.message) {
          shopify.toast.show(response.data.message);
        }
        fetchproduct(status, query, orderBy, perPageValue, current_page);
      
    } catch (error) {
      console.error("Error sending import request:", error);
    }
  };

  const handleModalVariants = async (variant) => {
    console.log("product ->> ", variant);
    if (activeModal) {
      setActiveModal(false);
      setvariants([]);
      return;
    }
    if (variant) {
      try {
        if (variant) {
          console.log("ifffffffffff");

          setvariants(variant);
        } else {
          setvariants([]);
          console.error("Failed to load variants:");
        }
      } catch (error) {
        console.error("Error fetching variants:", error);
        setvariants([]);
      }
    } else {
      setvariants([]);
    }
    setActiveModal((prev) => !prev);
  };

  const handleTabChange = (index) => {
    setSelectedTab(index);
  };

    useEffect(() => {
    const userData = user;
    if (Array.isArray(selectedResources) && selectedResources.length > 0) {
      if (userData.plan === 0) {
        if (selectedResources.length > 5) {
          //console.log(selectedResources);
        }
      }

      console.log(products);
      
      const filteredProductIdsUnblock = products
        .filter(
          (product) =>
            selectedResources.includes(product.id) &&
            product.status === "Ready to Import" &&
            product.block === 1,
        )
        .map((product) => product.id);
      const filteredProductIds = products
        .filter(
          (product) =>
            selectedResources.includes(product.id) &&
            product.status === "Ready to Import" &&
            product.block === 0,
        )
        .map((product) => product.id);
      if (userData.plan === 0) {
        if (userData.skuconsumed >= userData.skulimit) {
          // setUpgradeModalActive(true);
        } else {
          const importIds = filteredProductIds.slice(
            0,
            userData.skulimit - userData.skuconsumed,
          );
          setSelectedImport(importIds);
          // setImportedProductCount(importIds.length);
        }
      } else {
        setSelectedImport(filteredProductIds);
      }
    } else {
      // setImportedProductCount(0);
    }
  }, [selectedResources, products]);

  const activeTab = tabs[selectedTab];
  const filteredProducts = activeTab.status
    ? products.filter((p) => p.status === activeTab.status)
    : products;

  const resourceName = { singular: "product", plural: "products" };


  const handleSortChange = (value) => {
    setSortSelected(value);
    fetchproduct(status, query, value[0], perPageValue);
    console.log(value);
  };
  const handleCancelSearch = () => {
    setQuery("");
    console.log("handleCancelSearch");
    setQueryValue("");
    fetchproduct(status);
  };

  const rowMarkup = products.map(
    (
      {
        id,
        title,
        status,
        block,
        has_variation,
        shopifyproductid,
        image,
        variantCount,
        variants,
      },
      index,
    ) => (
      <IndexTable.Row
        id={id}
        key={id}
        selected={selectedResources.includes(id)}
        position={index}
        onClick={() => {
          console.log(id);
        }}
      >
        {isMobile ? (
          <>
            <IndexTable.Cell>
              {image ? (
                <img
                  src={image}
                  alt={"iamgeProduct"}
                  style={{ borderRadius: "5px" }}
                  width="60"
                  className="iamgeProduct"
                  height="110"
                />
              ) : (
                <FcPicture
                  style={{
                    width: "50px",
                    height: "50px",
                    color: "forestgreen",
                  }}
                />
              )}
            </IndexTable.Cell>
            <IndexTable.Cell>
              <Text
                variant="bodySm"
                as="p"
                style={{ wordBreak: "break-word", whiteSpace: "normal" }}
              >
                {title.split("\n").map((line, idx) => (
                  <span key={idx}>
                    {line}
                    <br />
                  </span>
                ))}
              </Text>

              <Link removeUnderline>{has_variation} variants</Link>

              {block == 0 ? <Badge>{status}</Badge> : <Badge>Block</Badge>}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  marginTop: "5px",
                  flexWrap: "wrap",
                }}
              >
                {shopifyproductid > 0 && (
                  <Tooltip content="View on Shopify" preferredPosition="below">
                    <a
                      // href={`https://admin.shopify.com/store/${storeName}/products/${shopifyproductid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={(e) => e.stopPropagation()}
                      style={{ display: "flex", alignItems: "center" }}
                    >
                      <FaShopify
                        style={{
                          width: "28px",
                          height: "28px",
                          color: "forestgreen",
                        }}
                      />
                    </a>
                  </Tooltip>
                )}
              </div>

              {status == "Ready to Import" && block == 0 && (
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    gap: "8px",
                    marginTop: "10px",
                  }}
                >
                  <Tooltip
                    content="Click here to import Amazon listings into your Shopify store."
                    preferredPosition="below"
                  >
                    <Button
                      variant="primary"
                      icon={ImportIcon}
                      style={{ flex: "1 1 auto", minWidth: "140px" }}
                    >
                      Import On Shopify
                    </Button>
                  </Tooltip>
                  {user.plan > 0 && (
                    <Tooltip
                      content="Block this product."
                      preferredPosition="mostSpace"
                    >
                      <Button style={{ flex: "1 1 auto", minWidth: "100px" }}>
                        Block
                      </Button>
                    </Tooltip>
                  )}
                </div>
              )}

              {status == "Imported" && (
                <>
                  {user.plan > 0 && (
                    <>
                      <div
                        style={{
                          display: "flex",
                          flexWrap: "wrap",
                          gap: "8px",
                        }}
                      >
                        <Tooltip content="Delete From Shopify">
                          <Button
                            tone="critical"
                            style={{ flex: "1 1 auto", minWidth: "120px" }}
                          >
                            Delete
                          </Button>
                        </Tooltip>
                      </div>
                    </>
                  )}
                </>
              )}

              {block == 1 && (
                <Tooltip
                  content="Unblock this product."
                  preferredPosition="mostSpace"
                >
                  <Button style={{ marginTop: "10px" }}>Unblock</Button>
                </Tooltip>
              )}
            </IndexTable.Cell>
          </>
        ) : (
          <>
            <IndexTable.Cell>
              {image ? (
                <img
                  src={image}
                  alt={"iamgeProduct"}
                  style={{ borderRadius: "5px" }}
                  width="50"
                  className="iamgeProduct"
                  height="50"
                />
              ) : (
                <FcPicture
                  style={{
                    width: "50px",
                    height: "50px",
                    color: "forestgreen",
                  }}
                />
              )}
            </IndexTable.Cell>
            <IndexTable.Cell>
              <Text variant="bodySm" as="p">
                {title.split("\n").map((line, idx) => (
                  <span key={idx}>
                    {line}
                    <br />
                  </span>
                ))}
              </Text>
            </IndexTable.Cell>
            <IndexTable.Cell>
              <Link
                // monochrome
                onClick={() => handleModalVariants(variants)}
                removeUnderline
              >
                {variantCount} variants
              </Link>
            </IndexTable.Cell>
            <IndexTable.Cell>
              {block == 0 ? (
                <Badge tone={getBadgeTone(status)}>{status}</Badge>
              ) : (
                <Badge tone={getBadgeTone("block")}>Block</Badge>
              )}
            </IndexTable.Cell>
            <IndexTable.Cell>
              {shopifyproductid > 0 && (
                <Tooltip content="view on Shopify" preferredPosition="below">
                  <a
                    // href={`https://admin.shopify.com/store/${storeName}/products/${shopifyproductid}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    onClick={(e) => e.stopPropagation()}
                    className="shopify-link"
                  >
                    <FaShopify
                      style={{
                        width: "40px",
                        height: "40px",
                        color: "forestgreen",
                      }}
                    />
                  </a>
                </Tooltip>
              )}
            </IndexTable.Cell>
            <IndexTable.Cell>
              {status == "Ready to Import" && block == 0 && (
                <div style={{ display: "flex", gap: "8px" }}>
                  <Tooltip
                    content="Click here to import Amazon listings into your Shopify store."
                    preferredPosition="below"
                  >
                    <Button
                      variant="primary"
                      icon={ImportIcon}
                      onClick={() => handleImportRequest(id)}
                    >
                      Import On shopify
                    </Button>
                  </Tooltip>
                  {user.plan > 0 && (
                    <Tooltip
                      content="Block this product."
                      preferredPosition="mostSpace"
                    >
                      <Button onClick={() => handleblockproduct(id)}>
                        Block
                      </Button>
                    </Tooltip>
                  )}
                </div>
              )}
              {status == "Imported" && (
                <>
                  {user.plan > 0 && (
                    <>
                      <div style={{ display: "flex", gap: "8px" }}>
                        <Tooltip content="Delete From Shopify">
                          <Button tone="critical">Delete</Button>
                        </Tooltip>
                      </div>
                    </>
                  )}
                </>
              )}

              {block == 1 && (
                <Tooltip
                  content="Unblock this product."
                  preferredPosition="mostSpace"
                >
                  <Button onClick={() => handleunblockproduct(id)}>
                    Unblock
                  </Button>
                </Tooltip>
              )}
            </IndexTable.Cell>
          </>
        )}
      </IndexTable.Row>
    ),
  );

  let content;
  if (!productData) {
    content = (
      <Card>
        <LegacyCard subdued>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
        </LegacyCard>
        <LegacyCard subdued>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
        </LegacyCard>
        <LegacyCard subdued>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
        </LegacyCard>
        <LegacyCard subdued>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
          <LegacyCard.Section>
            <SkeletonBodyText lines={2} />
          </LegacyCard.Section>
        </LegacyCard>
      </Card>
    );
  } else if (products.length === 0) {
    if (totalProduct == 0) {
      content = (
        <Card>
          {" "}
          <EmptyState
            heading="Product Not Found On Amazon"
            image="https://cdn.shopify.com/shopifycloud/web/assets/v1/vite/client/en/assets/empty-state-personalized-Bu4xlcHV0rQu.svg"
            fullWidth
          >
            <Text variant="bodyLg" as="p">
              You currently have no products available in your{" "}
              <strong>Amazon store.</strong> Please create a product to
              continue.
            </Text>
          </EmptyState>
        </Card>
      );
    } else {
      content = (
        <Card>
          <EmptyState
            heading="Product Not Found"
            image="https://cdn.shopify.com/s/files/1/0262/4071/2726/files/emptystate-files.png"
            fullWidth
          ></EmptyState>
        </Card>
      );
    }
  } else {
    content = (
      <>
        <IndexTable
          resourceName={resourceName}
          itemCount={products.length}
          selectedItemsCount={
            allResourcesSelected ? "All" : selectedResources.length
          }
          onSelectionChange={handleSelectionChange}
          headings={[
            { title: "Image" },
            { title: "Title" },
            { title: "Variations" },
            { title: "Status" },
            { title: "View On" },
            { title: "Action" },
          ]}
          promotedBulkActions={promotedBulkActions}
          selectable={selectable}
        >
          {rowMarkup}
        </IndexTable>
      </>
    );
  }
  return (
    <>
      <Page
        fullWidth
        title="Amazon Products"
        primaryAction={{
          content: "Fetch Amazon Products",
          icon: ImportIcon,
          onAction: fetchAmazonProducts,
        }}
      >
        <div style={{ marginBottom: 20 }}>
            
                  <Banner
                  >
                    <p>
                      Here you can view the products from your Amazon store and easily
                      import them into your Shopify store.
                    </p>
                  </Banner>
                  
                
              </div>
        <Modal
          open={activeModal}
          onClose={handleModalVariants}
          title="Product Variation List"
          primaryAction={{
            content: "Close",
            onAction: handleModalVariants,
          }}
        >
          <Modal.Section>
            {variants.length > 0 ? (
              <div style={{ width: "100%", overflowX: "auto" }}>
                <table
                  className="Polaris-Table"
                  style={{
                    width: "100%",
                    minWidth: "600px", // ensures proper layout on mobile
                    borderCollapse: "collapse",
                    marginTop: "10px",
                  }}
                >
                  <thead>
                    <tr style={{ backgroundColor: "#f6f6f7" }}>
                      <th style={headerStyle}>Option 1</th>
                      <th style={headerStyle}>Option 2</th>
                      <th style={headerStyle}>Sku</th>
                      <th style={headerStyle}>Quantity</th>
                      <th style={headerStyle}>Price</th>
                    </tr>
                  </thead>
                  <tbody>
                    {variants.map((variant, index) => (
                      <tr key={index}>
                        <td style={cellStyle}>{variant.option1val}</td>
                        <td style={cellStyle}>{variant.option2val}</td>
                        <td style={cellStyle}>{variant.sku}</td>
                        <td style={cellStyle}>{variant.quantity}</td>
                        <td style={cellStyle}>{variant.price}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <Text>No Variants Available</Text>
            )}
          </Modal.Section>
        </Modal>

        <LegacyCard>
          <IndexFilters
            sortOptions={sortOptions}
            sortSelected={sortSelected}
            queryValue={queryValue}
            queryPlaceholder="Search products"
            onQueryChange={handleFiltersQueryChange}
            onQueryClear={() => setQueryValue("")}
            onSort={handleSortChange}
            primaryAction={null}
            cancelAction={{
              content: "cancel",
              onAction: handleCancelSearch,
            }}
            tabs={tabs}
            selected={selectedTab}
            filters={[]}
            onSelect={(index) => {
              setSelectedTab(index);
              const selectedStatus = itemProducts[index];
              fetchproduct(selectedStatus);
            }}
            mode={mode}
            setMode={setMode}
            canCreateNewView={false}
          />
          {content}
          {/* <Tabs tabs={tabs} selected={selectedTab} onSelect={handleTabChange}> */}

          {/* </Tabs> */}
        </LegacyCard>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            backgroundColor: "#f6f6f7",
            padding: "10px 16px",
            borderTop: "1px solid #dfe3e8",
            borderBottom: "1px solid #dfe3e8",
          }}
        >
          {/* Pagination controls */}
          <Pagination
            onPrevious={() => {
              setCurrentPage(current_page - 1);

              fetchproduct(
                status,
                query,
                orderBy,
                perPageValue,
                current_page - 1,
              );
            }}
            onNext={() => {
              setCurrentPage(current_page + 1);
              fetchproduct(
                status,
                query,
                orderBy,
                perPageValue,
                current_page + 1,
              );
            }}
            hasPrevious={current_page !== 1}
            hasNext={lastProductNo < totalItems}
            type="table"
            label={`${firstProductNo}-${lastProductNo} of ${totalItems} products`}
          />
          {/* Dropdown for per page selection */}
          <pre style={{ marginLeft: "auto" }}>Items per page - </pre>
          <select
            name="perPageSelect"
            style={{
              height: "32px",
              padding: "4px 8px",
              fontSize: "14px",
              border: "1px solid #dfe3e8",
              borderRadius: "4px",
              backgroundColor: "#f6f6f7",
              color: "#000",
              appearance: "none",
              backgroundImage: `url("data:image/svg+xml;utf8,<svg fill='black' height='12' viewBox='0 0 24 24' width='12' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>")`,
              backgroundRepeat: "no-repeat",
              backgroundPosition: "right 8px center",
              backgroundSize: "12px",
              paddingRight: "24px",
              cursor: "pointer",
            }}
            value={perPageValue}
            onChange={handlePerPage}
          >
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
        </div>
        <Modal
          open={upgradeModalActive}
          onClose={toggleUpgradeModal}
          title="Upgrade Required"
          primaryAction={{
            content: "Upgrade Plan",
            onAction: () => {
              navigate("/app/plan");
            },
          }}
          secondaryActions={[
            {
              content: "Cancel",
              onAction: toggleUpgradeModal,
            },
          ]}
        >
          <Modal.Section>
            <TextContainer>
              <p>
                You have reached your import limit. Please upgrade your plan to
                import more products.
              </p>
            </TextContainer>
          </Modal.Section>
        </Modal>
      </Page>
    </>
  );
}
