import { truncateText } from "../../util";

export default (editor) => {
  const blockManager = editor.BlockManager;
  blockManager.add("product-detail", {
    label: `
      <div style="display: flex; flex-direction: column; align-items: center; gap: 5px;">
        <i class="bi bi-box-seam" style="font-size: 2.5rem;"></i>
        <span>Product Detail</span>
      </div>
    `,
    name: "product-detail",
    category: { label: "under dev", open: false },
    editable: true,
    content: { type: "product-detail", activeOnRender: true },
  });

  editor.Commands.add("open-product-detail-modal", {
    run(ed) {
      const selected = ed.getSelected();
      if (selected && selected.is("product-detail") && selected.openMainModal) {
        selected.openMainModal();
      }
    },
  });

  editor.DomComponents.addType("product-detail", {
    model: {
      defaults: {
        attributes: { class: "product-detail" },
        product: null,
        relatedProducts: [],
        script: function () {
          document.addEventListener("DOMContentLoaded", function () {
            var { app_slug, baseUrl, access_token } = getAppConfig();
            const $ = (selector) => document.querySelector(selector);
            const $all = (selector) => Array.from(document.querySelectorAll(selector));

            // Application State
            const appState = {
              cartItems: [],
              initialized: false,
            };

            // Load cart from localStorage
            async function loadCartFromLocalStorage() {
              try {
                const data = await JSON.parse(localStorage.getItem("cartData"));
                const storedCart = data[app_slug];
                if (storedCart) {
                  appState.cartItems = storedCart;
                } else {
                  appState.cartItems = [];
                }
              } catch (error) {
                console.error("Error loading cart from localStorage:", error);
                appState.cartItems = [];
              }
            }

            // Save cart to localStorage
            const saveCartToLocalStorage = () => {
              try {
                const existingData = localStorage.getItem("cartData");
                let parsedData = {};
                if (existingData) {
                  parsedData = JSON.parse(existingData);
                }
                parsedData[app_slug] = appState.cartItems;
                localStorage.setItem("cartData", JSON.stringify(parsedData));
              } catch (error) {
                console.error("Error saving cart to localStorage:", error);
              }
            };

            // Find cart item by product ID
            const findCartItemByIds = (productIds) => {
              return appState.cartItems.find((item) => item.ids === productIds);
            };

            // Add product to cart
            const addProductToCart = async (product) => {
              try {
                const existingCartItem = findCartItemByIds(product.ids);

                if (!existingCartItem) {
                  appState.cartItems = [
                    ...appState.cartItems,
                    {
                      ...product,
                      quantity: 1,
                    },
                  ];
                } else {
                  existingCartItem.quantity += 1;
                }
                saveCartToLocalStorage();
                updateProductButtonsDisplay(product.ids);
                showToast("success", "Item added to cart successfully!");
                updateCartBadgeCount();
              } catch (error) {
                console.error("Error adding product to cart:", error);
                showToast("error", "Failed to add item to cart");
              }
            };

            // Remove product from cart
            const removeProductFromCart = (productIds) => {
              try {
                appState.cartItems = appState.cartItems.filter((item) => item.ids !== productIds);
                saveCartToLocalStorage();
                updateProductButtonsDisplay(productIds);
                showToast("success", "Item removed from cart");
                updateCartBadgeCount();
              } catch (error) {
                console.error("Error removing product from cart:", error);
                showToast("error", "Failed to remove item from cart");
              }
            };

            // Update product card UI based on cart state
            const updateProductButtonsDisplay = (productIds) => {
              const productCards = $all(".product-card");
              productCards.forEach((card) => {
                const cardIds = card.dataset.ids;
                if (cardIds === productIds) {
                  const addToCartBtn = card.querySelector(".buy-now");
                  const removeFromCartBtn = card.querySelector(".remove-from-cart");
                  const isInCart = findCartItemByIds(productIds);
                  if (isInCart) {
                    if (addToCartBtn) addToCartBtn.style.display = "none";
                    if (removeFromCartBtn) removeFromCartBtn.style.display = "block";
                  } else {
                    if (addToCartBtn) addToCartBtn.style.display = "block";
                    if (removeFromCartBtn) removeFromCartBtn.style.display = "none";
                  }
                }
              });
            };

            // Fetch product details from URL parameter
            const fetchProductDetails = async () => {
              try {
                const productUrlParams = new URLSearchParams(window.location.search);
                const productId = productUrlParams.get("productIds");

                if (!productId) {
                  showToast("error", "Product ID not found in URL");
                  return;
                }

                const response = await fetch(
                  `${baseUrl}workspace/get_product_with_related?app_slug=${app_slug}&ids=${productId}`
                );
                const result = await response.json();

                if (result.status === "success") {
                  return result;
                } else {
                  showToast("error", result.message || "Failed to fetch product details");
                  return null;
                }
              } catch (error) {
                console.error("Error fetching product details:", error);
                showToast("error", "Failed to fetch product details");
                return null;
              }
            };

            // Fetch related products from same category
            const fetchRelatedProducts = async (categoryId) => {
              try {
                const response = await fetch(
                  `${baseUrl}workspace/get_products_by_category?app_slug=${app_slug}&category=${categoryId}`
                );
                const result = await response.json();

                if (result.status === "success") {
                  return result.products.filter((product) => product.ids !== currentProductId);
                } else {
                  showToast("error", result.message || "Failed to fetch related products");
                  return [];
                }
              } catch (error) {
                console.error("Error fetching related products:", error);
                showToast("error", "Failed to fetch related products");
                return [];
              }
            };

            // Update DOM with product details
            const updateProductDetail = (product) => {
              if (!product) return;

              const hasDiscount = product.discount && product.discountPercent > 0;
              const discountedPrice = hasDiscount
                ? (product.price * (1 - product.discountPercent / 100)).toFixed(2)
                : product.price.toFixed(2);

              // Update main product details
              $(".product-image").src = product.image || "https://placehold.co/400x400";
              $(".product-title").textContent = product.name;
              $(".current-price").textContent = `$${discountedPrice}`;

              if (hasDiscount) {
                $(".original-price").textContent = `$${product.price.toFixed(2)}`;
                $(".discount-badge").textContent = `Save $${((product.price * product.discountPercent) / 100).toFixed(
                  2
                )}`;
              } else {
                $(".original-price").style.display = "none";
                $(".discount-badge").style.display = "none";
              }

              $(".product-description").textContent = product.description || "No description available";

              // Update add to cart button
              const addToCartBtn = $(".add-to-cart-btn");
              addToCartBtn.textContent = `Add to Cart • $${discountedPrice}`;
              addToCartBtn.onclick = () => addProductToCart(product);
            };

            // Update related products section
            const updateRelatedProducts = (products) => {
              if (!products || products.length === 0) {
                $(".related-products").style.display = "none";
                return;
              }

              const relatedGrid = $(".related-grid");
              if (!relatedGrid) return;

              relatedGrid.innerHTML = products
                .slice(0, 4)
                .map((product) => {
                  const hasDiscount = product.discount && product.discountPercent > 0;
                  const discountedPrice = hasDiscount
                    ? (product.price * (1 - product.discountPercent / 100)).toFixed(2)
                    : product.price.toFixed(2);

                  return `
                  <div class="related-product" data-ids="${product.ids}">
                    <img src="${product.image || "https://placehold.co/200x200"}" alt="${
                    product.name
                  }" class="related-image">
                    <h3 class="related-name">${truncateText(product.name, 20)}</h3>
                    <div class="related-price-container">
                      ${
                        hasDiscount
                          ? `<div class="rl-discount-badge"> 
                               ${product.discountPercent} off
                            </div>`
                          : ""
                      }
                      ${
                        hasDiscount
                          ? `<span class="related-original-price">$${parseFloat(product.price).toFixed(2)}</span>`
                          : ""
                      }
                      <span class="related-current-price">$${discountedPrice}</span>
                    </div>
                    <button class="related-add-btn">Add to Cart</button>
                  </div>
                `;
                })
                .join("");

              // Add event listeners to related product buttons
              $all(".related-add-btn").forEach((button) => {
                const productId = button.closest(".related-product").dataset.ids;
                const product = products.find((p) => p.ids === productId);
                if (product) {
                  button.onclick = () => addProductToCart(product);
                }
              });
            };

            // Initialize
            const init = async () => {
              await loadCartFromLocalStorage();

              const response = await fetchProductDetails();
              if (response) {
                updateProductDetail(response.product);
                updateRelatedProducts(response.related_products);
              }
            };

            init();
            function updateCartBadgeCount() {
              const cartBadge = $(".cart-badge");
              if (cartBadge) {
                const totalItems = appState.cartItems.reduce((sum, item) => sum + item.quantity, 0);
                cartBadge.textContent = totalItems > 0 ? totalItems : "0";
              }
            }

            document.querySelector(".pd-back-button").addEventListener("click", () => {
              window.history.back();
            });
          });
        },
        components: [],
        styles: `
          /* Reset and base styles */
          .product-detail * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
          }
          
          .product-detail {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            line-height: 1.5;
            color: #333;
            background-color: #fff;
            padding: 0 10px;
          }
          
          .product-detail img {
            max-width: 100%;
            height: auto;
            display: block;
            padding: 30px;
          }
          
          .product-detail button {
            cursor: pointer;
            font-family: inherit;
          }
          
          /* Product detail styles */
          .product-container {
            max-width: 480px;
            margin: 0 auto;
            background-color: #fff;
          }
          
          .product-image-container {
            position: relative;
            padding:50px 30px;
          }
          
          .product-image {
            width: 100%;
            height: 320px;
            object-fit: cover;
          }
          
          .pd-back-button {
            background-color: black;
            color: white;
            border: none;
            padding: 9px;
            border-radius: 100%;
            cursor: pointer;
            position: absolute;
            top: 30px;
            right: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 35px;
            width: 35px;
          }
          
          .discount-badge {
            position: absolute;
            top: 35px;
            left: 20px;
            background-color: #e53e3e;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
          }
          .rl-discount-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background-color: rgb(66, 149, 29);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
          }
          .discount-percentage {
            background-color: rgb(66, 149, 29);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
          }
          
          .product-details {
            padding: 16px;
          }
          
          .product-title {
            font-size: 16px;
            font-weight: 700;
            margin-bottom: 16px;
          }
          
          .price-container {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 16px;
          }
          
          .current-price {
            font-size: 26px;
            font-weight: 700;
          }
          
          .original-price {
            font-size: 18px;
            color: #666;
            text-decoration: line-through;
          }
          
          .stock-status {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 16px;
          }
          
          .stock-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #48bb78;
          }
          
          .stock-text {
            font-size: 14px;
            font-weight: 500;
            color: #48bb78;
          }
          
          .section-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
          }
          
          .product-description {
            font-size: 15px;
            color: #4b5563;
            margin-bottom: 24px;
          }
          
          .add-to-cart-btn {
            width: 100%;
            height: 48px;
            background-color: #3b82f6;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            transition: background-color 0.2s;
          }
          
          .add-to-cart-btn:hover {
            background-color: #2563eb;
          }
          
          /* Related products section */
          .related-products {
            padding: 16px;
            background-color: #f9fafb;
          }
          
          .related-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 16px;
          }
          
          .related-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
          }
          
          .related-product {
            position: relative;
            background-color: white;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
          }
          
          .related-image {
            width: 100%;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 12px;
          }
          
          .related-name {
            font-size: 13px;
            font-weight: 500;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 21px;
          }
          
          .related-price-container {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
          }
          
          .related-current-price {
            font-size: 14px;
            font-weight: 600;
          }
          
          .related-original-price {
            font-size: 12px;
            color: #666;
            text-decoration: line-through;
          }
          
          .related-add-btn {
            width: 100%;
            height: 32px;
            background-color: #3b82f6;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
          }
        `,
        stylable: false,
        draggable: true,
        droppable: false,
        traits: [
          {
            type: "button",
            label: "Manage Products",
            text: "Open Manager",
            full: true,
            name: "manage-products",
            command: "open-product-detail-modal",
          },
        ],
      },

      init() {
        const editor = this.em;
        const component = this;
        let mainModal;
        let init = false;

        const updateComponents = () => {
          this.components([
            {
              tagName: "div",
              attributes: { class: "product-container" },
              components: [
                // Product Image
                {
                  tagName: "div",
                  attributes: { class: "product-image-container" },
                  components: [
                    {
                      tagName: "img",
                      attributes: {
                        class: "product-image",
                        src: "https://placehold.co/400x400",
                        alt: "Product image",
                      },
                    },
                    {
                      tagName: "button",
                      attributes: {
                        class: "pd-back-button",
                      },
                      components: [
                        {
                          tagName: "i",
                          attributes: { class: "bi bi-arrow-left" },
                        },
                      ],
                    },
                    {
                      tagName: "div",
                      attributes: { class: "discount-badge" },
                      content: "15% off",
                    },
                  ],
                },

                // Product Details
                {
                  tagName: "div",
                  attributes: { class: "product-details" },
                  components: [
                    // Title
                    {
                      tagName: "h1",
                      attributes: { class: "product-title" },
                      content: "Product Name",
                    },

                    // Price
                    {
                      tagName: "div",
                      attributes: { class: "price-container" },
                      components: [
                        {
                          tagName: "span",
                          attributes: { class: "original-price" },
                          content: "$399.99",
                        },
                        {
                          tagName: "span",
                          attributes: { class: "current-price" },
                          content: "$299.99",
                        },
                        {
                          tagName: "span",
                          attributes: { class: "discount-percentage" },
                          content: "25% OFF",
                        },
                      ],
                    },

                    // Stock Status
                    {
                      tagName: "div",
                      attributes: { class: "stock-status" },
                      components: [
                        {
                          tagName: "div",
                          attributes: { class: "stock-dot" },
                        },
                        {
                          tagName: "span",
                          attributes: { class: "stock-text" },
                          content: "In Stock",
                        },
                      ],
                    },

                    // Description
                    {
                      tagName: "div",
                      components: [
                        {
                          tagName: "h3",
                          attributes: { class: "section-title" },
                          content: "Description",
                        },
                        {
                          tagName: "p",
                          attributes: { class: "product-description" },
                          content: "Product description goes here.",
                        },
                      ],
                    },

                    // Add to Cart
                    {
                      tagName: "button",
                      attributes: { class: "add-to-cart-btn" },
                      content: "Add to Cart - $299.99",
                    },
                  ],
                },

                // Related Products
                {
                  tagName: "div",
                  attributes: { class: "related-products" },
                  components: [
                    {
                      tagName: "h2",
                      attributes: { class: "related-title" },
                      content: "You might also like",
                    },
                    {
                      tagName: "div",
                      attributes: { class: "related-grid" },
                      components: [
                        // Related Product 1
                        {
                          tagName: "div",
                          attributes: { class: "related-product" },
                          components: [
                            {
                              tagName: "img",
                              attributes: {
                                class: "related-image",
                                src: "https://placehold.co/200x200",
                                alt: "Related product",
                              },
                            },
                            {
                              tagName: "h3",
                              attributes: { class: "related-name" },
                              content: "Related Product 1",
                            },
                            {
                              tagName: "div",
                              attributes: { class: "related-price-container" },
                              components: [
                                {
                                  tagName: "div",
                                  attributes: { class: "rl-discount-badge" },
                                  content: "Save $100",
                                },
                                {
                                  tagName: "span",
                                  attributes: { class: "related-original-price" },
                                  content: "$249.99",
                                },
                                {
                                  tagName: "span",
                                  attributes: { class: "related-current-price" },
                                  content: "$199.99",
                                },
                              ],
                            },
                            {
                              tagName: "button",
                              attributes: { class: "related-add-btn" },
                              content: "Add to Cart",
                            },
                          ],
                        },

                        // Related Product 2
                        {
                          tagName: "div",
                          attributes: { class: "related-product" },
                          components: [
                            {
                              tagName: "img",
                              attributes: {
                                class: "related-image",
                                src: "https://placehold.co/200x200",
                                alt: "Related product",
                              },
                            },
                            {
                              tagName: "h3",
                              attributes: { class: "related-name" },
                              content: "Related Product 2",
                            },
                            {
                              tagName: "div",
                              attributes: { class: "related-price-container" },
                              components: [
                                {
                                  tagName: "div",
                                  attributes: { class: "rl-discount-badge" },
                                  content: "10% off",
                                },
                                {
                                  tagName: "span",
                                  attributes: { class: "related-original-price" },
                                  content: "$179.99",
                                },
                                {
                                  tagName: "span",
                                  attributes: { class: "related-current-price" },
                                  content: "$149.99",
                                },
                              ],
                            },
                            {
                              tagName: "button",
                              attributes: { class: "related-add-btn" },
                              content: "Add to Cart",
                            },
                          ],
                        },
                      ],
                    },
                  ],
                },
              ],
            },
          ]);
        };

        const openMainModal = () => {
          mainModal = editor.Modal;
          mainModal.setTitle("Product Detail Settings");
          mainModal.setContent(`
            <div style="padding: 20px;">
              <h3>Product Detail Page</h3>
              <p>This component will automatically fetch product details based on URL parameters.</p>
              <p>Example URL: yoursite.com/product?product_id=PRODUCT_ID</p>
            </div>
          `);
          mainModal.open();
        };

        this.openMainModal = openMainModal;
        updateComponents();
      },
    },
  });
};



add prefix pds in all classes in style and html everywhere so that it will not conflict with any other and return me full code to copy and paste