import React, { useState } from 'react';
import { useStoreSelector } from '../../App';
import Accordion from '../../components/Accordion/Accordion';
import {
  getActualAttributes,
  getActualpriceAdditional,
} from '../../store/selectors/selectors';
import {
  actualAttributes as attributesTitle,
  AttributesT,
} from '../../utils/constants';
import { ComponentControl } from '../ComponentControl/ComponentControl';
import s from './Interface.module.scss';
import { useThreekitInitStatus } from '@threekit-tools/treble';
import { DefaultBtn } from './../DefaultBtn/DefaultBtn';
import { ShopItem } from './../ShopItem/ShopItem';
import { useEffect } from 'react';
import { SavedConfig } from './../SavedConfig/SavedConfig';
import { useProductCache } from '@threekit-tools/treble/dist';

const { AccordionItem } = Accordion;

export const Interface = ({ ...props }) => {
  const { returnCartInfo } = props;
  const hasLoaded = useThreekitInitStatus();

  const activeCategory: any = attributesTitle;
  const actualAttributes: any = useStoreSelector(getActualAttributes);
  const actualpriceAdditional: any = useStoreSelector(getActualpriceAdditional);

  const [configActiveMenu, setConfigActiveMenu]: any = useState(true);
  const [actualPrice, setActualPrice]: any = useState(0);
  const [actualParameters, setActualParameters]: any = useState({
    playerHeight: 0,
    windowWidth: window.innerWidth,
  });

  function getActualPrice() {
    let price = 0;
    Object.keys(actualAttributes).map((name: any) => {
      const actualName: AttributesT = name;
      const quantity: number = actualAttributes[actualName].shopInfo.quantity;
      price += actualAttributes[actualName].price * quantity;
    });
    setActualPrice(price.toFixed(2));
  }

  {
    (function () {
      window.addEventListener('resize', resizeThrottler, false);

      let resizeTimeout: any;
      function resizeThrottler() {
        // ignore resize events as long as an actualResizeHandler execution is in the queue
        //@ts-ignore
        if (!resizeTimeout && window.innerWidth <= 992) {
          resizeTimeout = setTimeout(function () {
            resizeTimeout = null;
            actualResizeHandler();
            // The actualResizeHandler will execute at a rate of 15fps
          }, 66);
        }
      }

      function actualResizeHandler() {
        // handle the resize event
        //@ts-ignore
        if (window.playerHeight) {
          //@ts-ignore
          let playerHeight = window.playerHeight;
          // height: calc(100vh - 138px - 592px);
          setActualParameters({
            playerHeight: playerHeight,
            windowWidth: window.innerWidth,
          });
        }
      }
    })();
  }

  useEffect(() => {
    //@ts-ignore
    let playerHeight = window.playerHeight;
    setActualParameters({
      playerHeight: playerHeight,
      windowWidth: window.innerWidth,
    });
    //@ts-ignore
  }, [window.playerHeight]);

  useEffect(() => {
    getActualPrice();
  }, [configActiveMenu]);

  useEffect(() => {
    if (hasLoaded) {
      getActualPrice();
    }
  }, [actualAttributes]);

  function testFetch() {
    // const url =
    //   'https://quadratec-threekit-api.herokuapp.com/get-ar/Jeep 4 door JL/?Lift="2 inch"&Wheels=WHL Quad Rubicon Xtreme Silver';
    // fetch(`/api/get_ar/$${url}`)
    //   .then((resp) => resp.json())
    //   .then(function (data) {
    //     console.log('data: ', data);
    //   })
    //   .catch(function (error) {
    //     console.log(error);
    //   });
  }

  function addToCart() {
    const arrayOfMetaData: any = [];
    const nameJeep = window.threekit.configurator.getMetadata().name;
    Object.keys(actualAttributes).forEach((key: any) => {
      if (actualAttributes[key].shopInfo.quantity >= 1) {
        let obg: any = {
          fcid: undefined,
          node_id: undefined,
          product_id: undefined,
          sku: undefined,
        };
        if (
          key === 'Lift' ||
          key === 'Wrangler Model' ||
          key === 'Shock Options'
        ) {
          if (key === 'Shock Options') {
            obg = {
              ...obg,
              label: 'Lift',
              id: actualAttributes[key].id,
              quantity: actualAttributes[key].shopInfo.quantity,
              category: key,
            };
            if (actualAttributes[key].id) {
              obg = {
                ...obg,
                ...actualpriceAdditional[actualAttributes[key].id],
              };
            }
            arrayOfMetaData.push(obg);
          }
        } else {
          if (actualAttributes[key].activeItemId) {
            obg = {
              ...obg,
              label: actualAttributes[key].activeItem,
              id: actualAttributes[key].activeItemId,
              quantity: actualAttributes[key].shopInfo.quantity,
              category: key,
            };
            obg = {
              ...obg,
              ...actualpriceAdditional[actualAttributes[key].activeItemId],
            };

            arrayOfMetaData.push(obg);
          }
          // else {
          //   obg = {
          //     ...obg,
          //     label: actualAttributes[key].activeItem,
          //     quantity: actualAttributes[key].shopInfo.quantity,
          //     category: key,
          //   };
          //   if (actualAttributes[key].activeItemId) {
          //     obg = {
          //       ...obg,
          //       ...actualpriceAdditional[actualAttributes[key].activeItemId],
          //     };
          //   }
          //   arrayOfMetaData.push(obg);
          // }
        }
      }
    });
    const jsonMessage = {
      type: 'ADD_TO_CART',
      jeepName: nameJeep,
      paintColor: actualAttributes['Paint color'].activeItem,
      data: arrayOfMetaData,
    };
    console.log('jsonMessage: ', jsonMessage);
    if (returnCartInfo) {
      returnCartInfo(jsonMessage);
    }
    window.parent.postMessage(
      jsonMessage,
      '*' //or "www.parentpage.com"
    );
  }

  return (
    <div
      className={s.wrapper}
      style={
        actualParameters.windowWidth <= 992
          ? {
              height: `calc(var(--vh, 1vh) * 100 - 109px - ${actualParameters.playerHeight}px)`,
              // height: `calc(100vh - 138px - ${actualParameters.playerHeight}px)`,
            }
          : {}
      }
    >
      <div className={`${s.config} ${configActiveMenu ? s.active : ''}`}>
        <div className={s.title} onClick={() => testFetch()}>
          Change Jeep appearance
        </div>
        <div className={s.subtitle}>
          Choose parts that fit your Jeep perfectly
        </div>
        {hasLoaded && actualAttributes && (
          <div className={s.content}>
            <Accordion>
              {Object.keys(actualAttributes).map((name: any) => {
                const actualName: AttributesT = name;
                let activeItem = actualAttributes[actualName].activeItem;
                if (actualName === 'Lift') {
                  activeItem = actualAttributes['Shock Options'].activeItem;
                }
                // const quantity: number =
                //   actualAttributes[actualName].shopInfo.quantity;

                if (activeCategory[name]) {
                  return (
                    <AccordionItem
                      activeItem={activeItem}
                      defaultItem={actualAttributes[actualName].defaultItem}
                      cameraPosition={
                        actualAttributes[actualName].cameraPosition
                      }
                      label={attributesTitle[actualName]}
                      actualName={actualName}
                      key={`accordion-${name}`}
                    >
                      <div className={`${s.product__block} ${s[actualName]}`}>
                        <ComponentControl attr={name} />
                      </div>
                    </AccordionItem>
                  );
                }
              })}
            </Accordion>
          </div>
        )}
        {hasLoaded && actualAttributes && (
          <div className={`${s.offer__wrapper}`}>
            <div className={s.offer_info}>
              <div className={s.offer_title}>
                <span className={s.desktop}>Total Summary</span>
                <span className={s.mobile}>Total</span>
              </div>
              <div className={s.offer_price}>${actualPrice}</div>
            </div>
            <div
              className={`${s.offer_btn} ${actualPrice == 0 ? s.disable : ''}`}
              onClick={() => setConfigActiveMenu(false)}
            >
              <span className={s.desktop}>Review your build</span>
              <span className={s.mobile}>Review build</span>
            </div>
          </div>
        )}
      </div>
      <div className={`${s.shop} ${!configActiveMenu ? s.active : ''}`}>
        <div className={s.shop_title__wrapper}>
          <div className={s.title}>Review your build</div>

          <div className={s.shop_save_config}>
            <SavedConfig disableAr={true} />
          </div>
        </div>
        {hasLoaded && actualAttributes && actualPrice != 0 ? (
          <>
            <div className={s.string_title}>Accessories</div>
            <div className={s.content}>
              {Object.keys(actualAttributes).map((name: any) => {
                const actualName: AttributesT = name;
                const quantity: number =
                  actualAttributes[actualName].shopInfo.quantity;

                let activeCheck =
                  actualAttributes[actualName].defaultItem ===
                  actualAttributes[actualName].activeItem;

                if (
                  !activeCheck &&
                  actualAttributes[actualName].activeItem &&
                  actualName != 'Paint color'
                ) {
                  return (
                    <ShopItem
                      name={name}
                      type={'asset'}
                      actualPrice={actualPrice}
                      info={actualAttributes[actualName]}
                      label={attributesTitle[actualName]}
                      setConfigActiveMenu={setConfigActiveMenu}
                      quantity={quantity}
                      key={`accordion-${name}`}
                    />
                  );
                }
              })}
            </div>
          </>
        ) : (
          <>
            <div className="test">123</div>
            {}
          </>
        )}
        {hasLoaded && actualAttributes && (
          <div className={`${s.offer__wrapper} ${s.shop_content}`}>
            <div className={s.total__wrapper}>
              <div className={s.total_title}>Total Summary</div>
              <div className={s.total_price}>${actualPrice}</div>
            </div>
            <div className={s.btn__wrapper}>
              <div
                className={s.back_btn}
                onClick={() => setConfigActiveMenu(true)}
              >
                Back to Config
              </div>
              <div
                className={`${s.next_btn} ${actualPrice == 0 ? s.disable : ''}`}
                onClick={() => addToCart()}
              >
                Go to Checkout
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
