import * as React from 'react';
import {
  useContext, useRef, useMemo, useEffect, useState,
} from 'react';
import { style, classes } 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 ProductModalContainer from './ProductModalContainer';
import AttributionFooter from '../../AttributionFooter';

export default function ProductModal() {
  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 { exactProducts, similarProducts } = useMemo(
    () => filterExactOrSimilarProducts(
      settings.max_exact_products_displayed,
      settings.max_similar_products_displayed,
      products,
      productsLinked.exact,
      productsLinked.similar,
    ),
    [settings, products, productsLinked],
  );

  const showAttribution = settings.show_attribution !== false; // default to true

  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 === 'modal' && (products?.length ?? 0) > 0

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

  return (
    <div className={classes(styles.wrapper, `${config.classPrefix}-postviewer-details`)}>
      <div className={styles.container} ref={containerRef}>
        <div style={styles.contentArea}>
          {/* Products panel */}
          <div style={{ ...styles.panel, ...(confirmedProduct ? styles.fadeOut : styles.fadeIn) }}>
            {showProducts ? (
              <>
                {/* Case 1: Settings : 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'} />
                    <ProductModalContainer
                      products={exactProducts}
                      parentMedia={context.post!}
                      isSingleSection={true}
                      onAddToCart={handleAddToCart}
                    />
                  </>
                ) : null}

                {/* Case 2: Settings : 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'} />
                    <ProductModalContainer
                      products={similarProducts}
                      parentMedia={context.post!}
                      isSingleSection={true}
                      onAddToCart={handleAddToCart}
                    />
                  </>
                ) : null}

                {/* Case 3: Settings : 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'}
                        />
                        <ProductModalContainer
                          products={exactProducts}
                          parentMedia={context.post!}
                          isSingleSection={similarProducts.length === 0}
                          onAddToCart={handleAddToCart}
                        />
                      </>
                    ) : null}

                    {similarProducts.length > 0 ? (
                      <>
                        <Header
                          isMobile={isMobile}
                          text={settings.more_like_this_text ?? config.moreLikeThisText ?? 'More like this'}
                        />
                        <ProductModalContainer
                          products={similarProducts}
                          parentMedia={context.post!}
                          isSingleSection={exactProducts.length === 0}
                          onAddToCart={handleAddToCart}
                        />
                      </>
                    ) : null}
                  </>
                ) : null}
              </>
            ) : null}
          </div>

          {/* Confirmation panel */}
          <div style={{ ...styles.panel, ...(confirmedProduct ? styles.fadeIn : styles.fadeOut) }}>
            {confirmedProduct ? (
              <CartConfirmation
                product={confirmedProduct.product}
                isMobile={isMobile}
                cartUrl={config.cartUrl}
                cornerType={settings.thumbnail_corners}
                onContinue={() => setConfirmedProduct(null)}
              />
            ) : null}
          </div>
        </div>

        {showAttribution ? (
          <AttributionFooter
            classPrefix={config.classPrefix}
            type='modal'
          />) : null}

      </div>
    </div>
  );
}

const styles = {
  wrapper: style({
    height: '100%',
    display: 'flex',
  }),

  container: style({
    fontFamily: "'Fustat', sans-serif",
    color: '#231F20',
    fontSize: 16,
    width: '100%',
    wordBreak: 'break-word',
    boxSizing: 'border-box',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    maxHeight: '100%',
  }),

  contentArea: {
    flex: 1,
    position: 'relative' as const,
    minHeight: 0,
    overflow: 'hidden',
  },

  panel: {
    position: 'absolute' as const,
    inset: 0,
    padding: '15px 25px',
    boxSizing: 'border-box' as const,
    display: 'flex',
    flexDirection: 'column' as const,
  },

  fadeIn: {
    opacity: 1,
    transition: 'opacity 0.3s ease',
    pointerEvents: 'auto' as const,
    overflow: 'hidden' as const,
  },

  fadeOut: {
    opacity: 0,
    transition: 'opacity 0.3s ease',
    pointerEvents: 'none' as const,
    overflow: 'hidden' as const,
  },
};
