import Image from 'next/image';
import Link from '@/core/components/elements/Link/Link';
import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
// import { fetchPromoItemsSolr, fetchVariantSolr } from '../../../api/promoApi'


export const fetchPromoItemsSolr = async (type) => {
  // let query = type ? `type_value_s:${type}` : '*:*';
  let start = 0
  let rows = 100
  try {
    const queryParams = new URLSearchParams({ q: type });
    const response = await fetch(`/solr/promotion_program_lines/select?${queryParams.toString()}&rows=${rows}&start=${start}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    const promotions = await map(data.response.docs);
    return promotions;
  } catch (error) {
    console.error("Error fetching promotion data:", error);
    return [];
  }
};


const PromoList = ({ selectedPromo }) => {

  useEffect(() => {
    const loadPromo = async () => {
      setLoading(true);
      
      
      try {
        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`);
        setPromoItems(items);
        
        if (items.length === 0) {
          setPromoData([])
          setLoading(false);
          return;
          }
          
          const brandArray = Array.isArray(brand) ? brand : brand.split(',');
          const categoryArray = Array.isArray(category) ? category : category.split(',');
          
          const promoDataPromises = items.map(async (item) => {
            
            try { 
              let brandQuery = '';
              if (brand) {
                brandQuery = brandArray.map(b => `manufacture_name_s:${b}`).join(' OR ');
                brandQuery = `(${brandQuery})`;
              }
  
              let categoryQuery = '';
              if (category) {
                categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
                categoryQuery = `(${categoryQuery})`;
              }
  
              let priceQuery = '';
              if (priceFrom && priceTo) {
                priceQuery = `price_f:[${priceFrom} TO ${priceTo}]`;
              } else if (priceFrom) {
                priceQuery = `price_f:[${priceFrom} TO *]`;
              } else if (priceTo) {
                priceQuery = `price_f:[* TO ${priceTo}]`;
              }
  
              let combinedQuery = '';
              let combinedQueryPrice = `${priceQuery}`;
              if (brand && category && priceFrom || priceTo) {
                combinedQuery = `${brandQuery} AND ${categoryQuery} `;
              } else if (brand && category) {
                combinedQuery = `${brandQuery} AND ${categoryQuery}`;
              } else if (brand && priceFrom || priceTo) {
                combinedQuery = `${brandQuery}`;
              } else if (category && priceFrom || priceTo) {
                combinedQuery = `${categoryQuery}`;
              } else if (brand) {
                combinedQuery = brandQuery;
              } else if (category) {
                combinedQuery = categoryQuery;
              }
  
              if (combinedQuery && priceFrom || priceTo) {
                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                const product = response.response.docs[0];
                const product_id = product.id;
                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`);  
                return response2;
              }else if(combinedQuery){
                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                const product = response.response.docs[0];
                const product_id = product.id;
                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
                return response2;
              } else {
                const response = await fetchPromoItemsSolr(`id:${item.id}`);
                return response;
              }
            } catch (fetchError) {
              return [];
            }
          });

        const promoDataArray = await Promise.all(promoDataPromises);
        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        setPromoData(mergedPromoData);

        const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
          if (promoData) {
            const dataBrandCategory = promoData.map(async (item) => {
              let response;
              if(category){
                const categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
                response = await fetchVariantSolr(`id:${item.products[0].product_id} AND (${categoryQuery})`);
              }else{
                response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
              }
              

              if (response.response?.docs?.length > 0) {
                const product = response.response.docs[0];
                const manufactureNameS = product.manufacture_name;
                if (Array.isArray(manufactureNameS)) {
                  for (let i = 0; i < manufactureNameS.length; i += 2) {
                    const brand = manufactureNameS[i];
                    const qty = 1;
                    const existingBrandIndex = brandsData.findIndex(b => b.brand === brand);
                    if (existingBrandIndex !== -1) {
                      brandsData[existingBrandIndex].qty += qty;
                    } else {
                      brandsData.push({ brand, qty });
                    }
                  }
                }

                const categoryNameS = product.category_name;
                if (Array.isArray(categoryNameS)) {
                  for (let i = 0; i < categoryNameS.length; i += 2) {
                    const name = categoryNameS[i];
                    const qty = 1;
                    const existingCategoryIndex = categoriesData.findIndex(c => c.name === name);
                    if (existingCategoryIndex !== -1) {
                      categoriesData[existingCategoryIndex].qty += qty;
                    } else {
                      categoriesData.push({ name, qty });
                    }
                  }
                }
              }
            });

            return Promise.all(dataBrandCategory);
          }
        });

        await Promise.all(dataBrandCategoryPromises);
        setBrands(brandsData);
        setCategories(categoriesData);
        setLoading(false);

      } catch (loadError) {
        // console.error("Error loading promo items:", loadError)
        setLoading(false);
      }
    }

    if (slug) {
      loadPromo()
    }
  },[slug, brand, category, priceFrom, priceTo, currentPage]);

  let title = '';
  
  if (selectedPromo === 'Bundling') {
    title = 'Kombinasi Kilat Pilihan Kami!';
  } else if (selectedPromo === 'Loading') {
    title = 'Belanja Borong Pilihan Kami!';
  } else if (selectedPromo === 'Merchandise') {
    title = 'Gratis Merchandise Spesial Indoteknik';
  }

  return (
    <div>
      <h1 className='text-h-sm md:text-h-lg font-semibold mb-4'>{title}</h1>
      <div>DISINI CARD {selectedPromo}</div>
    </div>
  );
}

export default PromoList;
