import React, { useEffect, useRef, useState } from 'react';
import s from './ArStep1.module.scss';
import { SetModal } from '../../../store/actions/Settings';
import ArStep1_1 from '../../../assets/ArStep1_1';
import ArGood from '../../../assets/ArGood';
import ArBad from '../../../assets/ArBad';
import ArStep1_2 from '../../../assets/ArStep1_2';
import ArStep4_2 from '../../../assets/ArStep4_2';
import ArStep4_1 from '../../../assets/ArStep4_1';
import ArStep3_2 from '../../../assets/ArStep3_2';
import ArStep3_1 from '../../../assets/ArStep3_1';
import ArStep2_2 from '../../../assets/ArStep2_2';
import ArStep2_1 from '../../../assets/ArStep2_1';
import ArStep5_1 from '../../../assets/ArStep5_1';
import ArStep5_2 from '../../../assets/ArStep5_2';

import {
  getMobileOperatingSystem,
  MobileOs,
} from '../../../utils/helpFunctions';
import { useStoreDispatch } from '../../../App';
import { arApiNameJeeps, PAGE_NAME } from '../../../utils/constants';
import { useLocation } from 'react-router-dom';
import { QRCodeSVG } from 'qrcode.react';
const axios = require('axios');

function load3DModel() {
  var isMobile = {
    Android: function () {
      return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function () {
      return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function () {
      return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function () {
      return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function () {
      return navigator.userAgent.match(/IEMobile/i);
    },
    any: function () {
      return (
        isMobile.Android() ||
        isMobile.BlackBerry() ||
        isMobile.iOS() ||
        isMobile.Opera() ||
        isMobile.Windows()
      );
    },
  };

  if (isMobile.Android()) {
    document.location.href =
      'https://media.keyshot.com/scenes/envoy/envoy-opt.glb';
  } else if (isMobile.iOS()) {
    document.location.href =
      'https://media.keyshot.com/scenes/envoy/envoy.usdz';
  }

  // document.location.href = window.location.origin;
}

export type illustrationsT = {
  id: string;
  SvgIcon: any;
  title?: {
    text: string;
    Icon: any;
  };
};
export type stepItemsT = {
  id: string;
  subtitle: string;
  start?: boolean;
  illustrations: illustrationsT[];
};

export type currentOST = 'Android' | 'IOS' | 'unknown';
const stepItems: stepItemsT[] = [
  {
    id: 'stepItems1',
    subtitle: 'Select a well-lit area without any gloss or shiny materials.',
    illustrations: [
      {
        id: 'illustrations1',
        SvgIcon: () => <ArStep1_1 />,
        title: {
          text: 'Well-lit surface',
          Icon: () => <ArGood />,
        },
      },
      {
        id: 'illustrations2',
        SvgIcon: () => <ArStep1_2 />,
        title: {
          text: 'Poorly lit surface',
          Icon: () => <ArBad />,
        },
      },
    ],
  },
  {
    id: 'stepItems2',
    subtitle: 'Scan the surface as close as possible',
    illustrations: [
      {
        id: 'illustrations1',
        SvgIcon: () => <ArStep2_1 />,
        title: {
          text: 'Perfect distance',
          Icon: () => <ArGood />,
        },
      },
      {
        id: 'illustrations2',
        SvgIcon: () => <ArStep2_2 className={s.step_2_2} />,
        title: {
          text: 'Bad distance, too far',
          Icon: () => <ArBad />,
        },
      },
    ],
  },
  {
    id: 'stepItems3',
    subtitle: 'Choose an uneven area with a few physical objects there',
    illustrations: [
      {
        id: 'illustrations1',
        SvgIcon: () => <ArStep3_1 />,
        title: {
          text: 'Ideal Surface',
          Icon: () => <ArGood />,
        },
      },
      {
        id: 'illustrations2',
        SvgIcon: () => <ArStep3_2 />,
        title: {
          text: 'Bad Surface',
          Icon: () => <ArBad />,
        },
      },
    ],
  },
  {
    id: 'stepItems4',
    subtitle: 'Use One Finger to move Jeep around your space',
    illustrations: [
      {
        id: 'illustrations1',
        SvgIcon: () => <ArStep4_1 />,
      },
      {
        id: 'illustrations2',
        SvgIcon: () => (
          <img src="https://i.postimg.cc/wv8yGyzY/ar-Step5-1.png" alt="" />
        ),
      },
    ],
  },
  {
    id: 'stepItems5',
    subtitle: 'Use Two Finger to rotate and zoom vehicle 360°',
    start: true,
    illustrations: [
      {
        id: 'illustrations1',
        SvgIcon: () => <ArStep5_1 />,
      },
      {
        id: 'illustrations2',
        SvgIcon: () => (
          <img src="https://i.postimg.cc/fLctnzWt/ar-Step5-2.png" alt="" />
        ),
      },
    ],
  },
];

// {
//   id: 'illustrations1',
//   SvgIcon: () => (
//     <img src="https://i.postimg.cc/wv8yGyzY/ar-Step5-1.png" alt="" />
//   ),
// },
// {
//   id: 'illustrations2',
//   SvgIcon: () => (
//     <img src="https://i.postimg.cc/fLctnzWt/ar-Step5-2.png" alt="" />
//   ),
// },

export const ArStep1 = ({ ...parameters }: any) => {
  const dispatch = useStoreDispatch();
  let location = useLocation().pathname;

  const [actualStep, setActualStep] = useState(stepItems[0].id);
  const [arUrl, setArUrl] = useState('');
  const [link, setLink]: any = useState();
  const axios = require('axios');

  function nextStep(id: string) {
    setActualStep(id);
  }

  useEffect(() => {
    if (!parameters.ios && !parameters.android) {
      dispatch(
        SetModal({
          list: { loader: true },
          info: { text: 'Personalising you AR experience...' },
        })
      );
      //@ts-ignore
      const currentJeepNames: any = {
        'Wrangler JL ': 'Jeep2DoorJL',
        'Wrangler JL Unlimited': 'Jeep4DoorJL',
        Gladiator: 'JeepGladiator',
      };
      //@ts-ignore
      const threekitName = window.playerT.configurator.metadata.name;
      const jeepName = currentJeepNames[threekitName];
      const nameForApi = arApiNameJeeps[jeepName];
      //@ts-ignore
      let attr = window.threekit.configurator.getDisplayAttributes();

      const errorCategory = [''];
      let arUrl = '?';
      attr.map((item: any) => {
        const wrangler = 'Wrangler Model';
        const shock = 'Shock Options';
        const type = item.type;
        if (wrangler !== item.name && shock !== item.name) {
          if (type === 'Asset') {
            const categoryName = item.name;
            const method = item.value.assetId ? 'Asset' : 'Query';
            const value =
              method === 'Asset'
                ? item.value.assetId
                : item.value.query.metadata.option;
            const activeValue = item.values.find((val: any) => {
              if (method === 'Asset') {
                return value === val.assetId;
              } else if (method === 'Query') {
                return value === val.label;
              }
            });
            console.log('item: ', item);
            console.log('activeValue: ', activeValue);
            if (!errorCategory.includes(categoryName)) {
              if (activeValue.name !== 'None') {
                arUrl += `${categoryName}=${activeValue.name}&`;
              }
            }
          } else {
            if (!errorCategory.includes(item.name)) {
              if (item.value !== 'None') {
                arUrl += `${item.name}="${item.value}"&`;
              }
            }
          }
        }
      });
      arUrl = arUrl.slice(0, -1);
      const urlConfig = `https://quadratec-threekit-api.herokuapp.com/get-ar/${nameForApi}${arUrl}`;
      // const urlConfig = `https://quadratec-threekit-api.herokuapp.com/get-ar/${configName}/?Lift="2 inch"&Wheels=WHL Quad Rubicon Xtreme Silver`;

      axios
        .post(
          'https://quadratecbeta-z9cen.ondigitalocean.app/api/get_ar',
          { urlConfig },
          {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Content-Type': 'application/json',
            },
            withCredentials: false,
          }
        )
        .then(function (data: any) {
          const ios = data.data.data.usdz;
          const android = data.data.data.glb;
          setLink({
            ios,
            android,
          });
          dispatch(
            SetModal({
              list: { loader: false },
            })
          );
        })
        .catch(function (error: any) {
          console.log(error);
          dispatch(
            SetModal({
              list: { loader: false },
            })
          );
        });
    } else {
      const ios = parameters.ios;
      const android = parameters.android;
      setLink({
        ios,
        android,
      });
    }
  }, []);

  useEffect(() => {
    if (link) {
      const ios = parameters.ios ? parameters.ios : link.ios;
      const android = parameters.android
        ? parameters.android
        : `intent://arvr.google.com/scene-viewer/1.0?file=${link.android}&mode=ar_only#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;S.browser_fallback_url=https://developers.google.com/ar;end;`;
      if (MobileOs() === 'ios') {
        setArUrl(ios);
      } else if (MobileOs() === 'android') {
        setArUrl(android);
      } else if (MobileOs() === 'desktop') {
        let origin = window.location.origin;
        console.log('origin: ', origin);
        let url = `${origin}${location}?qr=true&ios=${ios}&android=${android}`;
        console.log('url: ', url);
        setArUrl(url);
      }
    }
  }, [link]);

  return (
    <>
      <div className={s.desktop__wrapper}>
        <div className={s.desktop_title}>View in Your Space</div>
        {/* {arUrl && <QRCode value={arUrl} />} */}
        {arUrl && (
          <div className={s.desktop_subtitle}>
            <QRCodeSVG value={arUrl} />
          </div>
        )}
        <div className={s.desktop_subtitle}>
          Scan the QR code with the camera app on your mobile device
        </div>
      </div>
      {stepItems &&
        link &&
        stepItems.map((item, index) => {
          if (item.id === actualStep) {
            return (
              <div
                className={`${s.wrapper} ${
                  !item.illustrations[0].title ? s.padding : ''
                }`}
                key={item.id}
              >
                <div className={s.animation__wrapper}>
                  {item.illustrations.map((illustration, indx) => (
                    <div
                      className={`${s.animation_item} ${s[illustration.id]}`}
                      key={illustration.id}
                    >
                      <div className={s.illustration}>
                        {<illustration.SvgIcon />}
                      </div>
                      {illustration.title && (
                        <div className={s.title}>
                          {<illustration.title.Icon />}
                          <span>{illustration.title.text}</span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>

                <div className={s.subtitle}>{item.subtitle}</div>
                <div className={s.dots}>
                  {stepItems.map((step, index) => {
                    return (
                      <div
                        className={`${s.dot} ${
                          step.id === actualStep ? s.active : ''
                        }`}
                        key={`${step.id}-dot-${index}`}
                      ></div>
                    );
                  })}
                </div>

                {item.start ? (
                  <a
                    className={s.btn_next}
                    rel="ar"
                    // onClick={() =>
                    //   popUp({ type: 'warning', message: 'Loading...' })
                    // }
                    href={arUrl}
                    // onClick={() => load3DModel()}
                  >
                    <img
                      alt="vr"
                      className={s.ar_img}
                      width={30}
                      src="https://cdn1.iconfinder.com/data/icons/augmented-reality-ar/64/AR-augmented-reality-360-VR-virtual-512.png"
                    ></img>
                    Start Scan
                  </a>
                ) : (
                  <div
                    className={s.btn_next}
                    onClick={() => nextStep(`stepItems${index + 2}`)}
                  >
                    Next
                  </div>
                )}

                {/* <div  onClick={loadArMode}></div> */}
                <a
                  className={s.skip}
                  // onClick={() =>
                  //   popUp({ type: 'warning', message: 'Loading...' })
                  // }
                  rel="ar"
                  href={arUrl}
                  // onClick={() => load3DModel()}
                >
                  Skip
                  <img
                    alt="vr"
                    className={s.ar_img}
                    width={30}
                    src="https://cdn1.iconfinder.com/data/icons/augmented-reality-ar/64/AR-augmented-reality-360-VR-virtual-512.png"
                  ></img>
                </a>
              </div>
            );
          }
        })}
    </>
  );
};
