import * as React from 'react';
import {
  useRef, useContext, useMemo, useEffect, useState, CSSProperties,
} from 'react';
import { style } from 'typestyle';
import { StoreContext } from '../../../../../services/store';
import { IMedia, IProduct } from '../../../../../types';
import filterExactOrSimilarProducts from '../helpers';
import Header from '../components/Header';
import CartConfirmation from '../components/CartConfirmation';
import ProductListContainer from './ProductListContainer';

export default function ProductList() {
  const context = useContext(StoreContext);
  const { products, productsLinked } = context.post!;
  const {
    data: { settings },
    config,
    isMobile,
  } = context;

  const containerRef = useRef<HTMLDivElement>(null);
  const productRefs = useRef<(HTMLDivElement | null)[]>([]);
  const [confirmedProduct, setConfirmedProduct] = useState<{ product: IProduct; media: IMedia } | null>(null);
  const hasProducts = (products?.length ?? 0) > 0;
  const showEmptyState = settings.shop_this_look_display !== 'none' && !hasProducts;
  const emptyStateText = config.noProductMatchText ?? 'No current product match';

  const { exactProducts, similarProducts } = useMemo(
    () => filterExactOrSimilarProducts(
      settings.max_exact_products_displayed,
      settings.max_similar_products_displayed,
      products,
      productsLinked.exact,
      productsLinked.similar,
    ),
    [settings, products, productsLinked],
  );

  useEffect(() => {
    productRefs.current = productRefs.current.slice(0, products?.length);
  }, [products]);

  if (config.displayCustomShopThisLook) {
    return config.displayCustomShopThisLook({
      react: React,
      products,
      media: context.post!,
      isMobile,
      context,
    });
  }

  const showProducts = settings.shop_this_look_display !== 'none' && hasProducts;

  const handleAddToCart = (product: IProduct, media: IMedia) => {
    if (config.addToCartHandler) {
      config.addToCartHandler({ product, media });
    }
    setConfirmedProduct({ product, media });
  };

  return (
    <div className={`${styles.outerContainer} ${config.classPrefix}-productlist`}>
      <div style={styles.sliderStyle(!!confirmedProduct)}>
        {/* Panel 1: Product list */}
        <div style={styles.panelStyle(isMobile)} ref={containerRef}>
        {showProducts ? (
          <>
            {/* Case 1: Display only exact products */}
            {settings.display_exact_products_only && !settings.display_similar_products_only ? (
              <>
                <Header isMobile={isMobile} text={settings.shop_this_look_text ?? config.shopThisLookText ?? 'Shop this look'} />
                <ProductListContainer
                  products={exactProducts}
                  startIndex={0}
                  onRefUpdate={(index, ref) => {
                    productRefs.current[index] = ref;
                  }}
                  parentMedia={context.post!}
                  onAddToCart={handleAddToCart}
                />
              </>
            ) : null}

            {/* Case 2: Display only similar products */}
            {!settings.display_exact_products_only && settings.display_similar_products_only ? (
              <>
                <Header isMobile={isMobile} text={settings.more_like_this_text ?? config.moreLikeThisText ?? 'More like this'} />
                <ProductListContainer
                  products={similarProducts}
                  startIndex={0}
                  onRefUpdate={(index, ref) => {
                    productRefs.current[index] = ref;
                  }}
                  parentMedia={context.post!}
                  onAddToCart={handleAddToCart}
                />
              </>
            ): null}

            {/* Case 3: Display both exact and similar products */}
            {!settings.display_exact_products_only && !settings.display_similar_products_only ? (
              <>
                {exactProducts.length > 0 ? (
                  <>
                    <Header
                      isMobile={isMobile}
                      text={settings.shop_this_look_text ?? config.shopThisLookText ?? 'Shop this look'}
                    />
                    <ProductListContainer
                      products={exactProducts}
                      startIndex={0}
                      onRefUpdate={(index, ref) => {
                        productRefs.current[index] = ref;
                      }}
                      parentMedia={context.post!}
                      onAddToCart={handleAddToCart}
                    />
                  </>
                ) : null}

                {similarProducts.length > 0 ? (
                  <>
                    <Header
                      isMobile={isMobile}
                      text={settings.more_like_this_text ?? config.moreLikeThisText ?? 'More like this'}
                    />
                    <ProductListContainer
                      products={similarProducts}
                      startIndex={exactProducts.length}
                      onRefUpdate={(index, ref) => {
                        productRefs.current[index] = ref;
                      }}
                      parentMedia={context.post!}
                      onAddToCart={handleAddToCart}
                    />
                  </>
                ) : null}
              </>
            ) : null}
          </>
        ) : null}

          {showEmptyState ? (
            <div className={`${styles.emptyState} ${config.classPrefix}-productlist-empty-state`}>
              {emptyStateText}
            </div>
          ) : null}
        </div>

        {/* Panel 2: Cart confirmation */}
        <div style={styles.panelStyle(isMobile)}>
          {confirmedProduct ? (
            <CartConfirmation
              product={confirmedProduct.product}
              isMobile={isMobile}
              cartUrl={config.cartUrl}
              cornerType={settings.thumbnail_corners}
              onContinue={() => setConfirmedProduct(null)}
            />
          ) : null}
        </div>
      </div>
    </div>
  );
}

const styles = {
  outerContainer: style({
    fontFamily: "'Fustat', sans-serif",
    color: '#231F20',
    fontSize: 16,
    height: '100%',
    overflow: 'hidden',
    $nest: {
      '&::-webkit-scrollbar': {
        width: '5px',
        height: '100%',
      },
      '&::-webkit-scrollbar-track': {
        background: '#E5E5E5',
        height: '100%',
      },
      '&::-webkit-scrollbar-thumb': {
        background: '#000000',
        borderRadius: 0,
        border: 'none',
        minHeight: '40px',
      },
    },
  }),
  emptyState: style({
    flex: 1,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
    color: '#6A6A6A',
    fontSize: 14,
    lineHeight: 1.4,
    padding: '24px 12px',
  }),

  sliderStyle: (confirmed: boolean): CSSProperties => ({
    display: 'flex',
    width: '200%',
    height: '100%',
    transform: confirmed ? 'translateX(-50%)' : 'translateX(0)',
    transition: 'transform 0.35s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
  }),

  panelStyle: (mobile: boolean): CSSProperties => ({
    width: '50%',
    height: '100%',
    overflowY: 'auto',
    overflowX: 'hidden',
    boxSizing: 'border-box',
    padding: mobile ? '0 15px 15px' : 15,
    wordBreak: 'break-word',
  }),
};
