import {
  useAttribute,
  useThreekitInitStatus,
} from '@threekit-tools/treble/dist';
import React, { useEffect, useState } from 'react';
import { AttributesT, dataLift } from '../../../utils/constants';
import s from './Lift.module.scss';
import productStyle from './../Product.module.scss';
import { getActualTitle, getProductParameters } from '../Product';
import { SimpleItem } from './../../SimpleItem/SimpleItem';
import { ShockItem } from './ShockItem/ShockItem';
import { useStoreDispatch, useStoreSelector } from '../../../App';
import {
  getActualAttributes,
  getActualPriceById,
} from './../../../store/selectors/selectors';
import { SetActiveItem } from '../../../store/actions/Settings';
import { getValidSortValues } from '../../../utils/helpFunctions';
import Error from '../../../assets/Error';

export function checkLiftOptions(actualAttr: any) {
  let result = false;
  const lift = actualAttr.Lift.activeItem;

  const wrangler = actualAttr['Wrangler Model'].activeItem;
  const shock = actualAttr['Shock Options'].shockActive;
  if (
    wrangler !== 'None' &&
    wrangler &&
    shock !== 'None' &&
    shock &&
    lift !== 'None'
  ) {
    result = true;
  }

  return result;
}
export const Lift = ({ ...props }) => {
  const name: AttributesT = props.name;
  const hasLoaded = useThreekitInitStatus();
  const dispatch = useStoreDispatch();
  const attributeInfo = useStoreSelector(getActualPriceById);
  const actualAttributes: any = useStoreSelector(getActualAttributes);
  console.log('actualAttributes123: ', actualAttributes);
  const [attribute, setAttribute]: any = useAttribute(name);
  const nameWrangler = 'Wrangler Model';
  const [attrWrangler, setAttrWrangler]: any = useAttribute(nameWrangler);
  const nameShock = 'Shock Options';
  const [attrShock, setAttrShock]: any = useAttribute(nameShock);
  const [allValue, setAllValue]: any = useState({
    Lift: 'None',
    'Wrangler Model': 'None',
    'Shock Options': 'None',
  });

  const lift = actualAttributes.Lift.activeItem;
  const wrangler = actualAttributes['Wrangler Model'].activeItem;

  const shock = actualAttributes['Shock Options'].shockActive;

  type errorT = {
    ifWranglerIsNone: string;
    ifShockIsNone: string;
  };
  const error: errorT = {
    ifWranglerIsNone:
      'Wrangler Model are required to continue the configuration',
    ifShockIsNone: 'Shock options are required to continue the configuration',
  };
  const [actualSortAttribute, setActualSortAttribute] = useState(
    attrShock.values
  );

  useEffect(() => {
    const liftIsActive = checkLiftOptions(actualAttributes);
    if (liftIsActive) {
      //@ts-ignore
      const jeepName = window.playerT.configurator.metadata.name;
      let currentPath = dataLift[jeepName][lift][wrangler][shock];
      if (currentPath) {
        const id = currentPath.id;
        const img = currentPath.img;
        const liftInfo = attributeInfo[id];

        dispatch(
          SetActiveItem({
            name: nameShock,
            data: {
              activeItem: liftInfo.name,
              price: liftInfo.price,
              id: id,
              img: img ? img : 'image-not-found.jpg',
            },
          })
        );
      } else {
        dispatch(
          SetActiveItem({
            name: nameShock,
            data: { activeItem: 'None' },
          })
        );
      }
    } else {
      dispatch(
        SetActiveItem({
          name: nameShock,
          data: { activeItem: 'None' },
        })
      );
    }
  }, [allValue]);

  useEffect(() => {
    const liftIsActive = checkLiftOptions(actualAttributes);
    const shock = actualAttributes['Shock Options'].shockActive;
    const lift = actualAttributes.Lift.activeItem;
    const wrangler = actualAttributes['Wrangler Model'].activeItem;
    if (hasLoaded) {
      setAllValue({
        Lift: lift,
        'Wrangler Model': wrangler,
        'Shock Options': shock,
      });
    }
  }, [
    actualAttributes.Lift,
    actualAttributes['Wrangler Model'],
    actualAttributes['Shock Options'].shockActive,
  ]);

  useEffect(() => {
    const lift = actualAttributes.Lift.activeItem;
    console.log('lift131231332312: ', lift);

    if (hasLoaded && lift === 'None') {
      // dispatch(
      //   SetActiveItem({
      //     name: nameShock,
      //     data: { shockActive: 'None', price: 0, shopInfo: { quantity: 1 } },
      //   })
      // );
      // dispatch(
      //   SetActiveItem({
      //     name: nameWrangler,
      //     data: { activeItem: 'None' },
      //   })
      // );
    } else if (hasLoaded && lift !== 'None') {
      // setAttribute(lift);
      // dispatch(
      //   SetActiveItem({
      //     name: 'Lift',
      //     data: { activeItem: lift },
      //   })
      // );
      // dispatch(
      //   SetActiveItem({
      //     name: nameShock,
      //     data: { shockActive: 'None', price: 0, shopInfo: { quantity: 1 } },
      //   })
      // );
      // dispatch(
      //   SetActiveItem({
      //     name: nameWrangler,
      //     data: { activeItem: 'None' },
      //   })
      // );
    }
  }, [actualAttributes.Lift]);

  useEffect(() => {
    const shock = actualAttributes['Shock Options'].activeItem;

    // if (hasLoaded && shock === 'None') {
    //   setAttribute('None');
    //   dispatch(
    //     SetActiveItem({
    //       name: 'Lift',
    //       data: { activeItem: 'None' },
    //     })
    //   );
    // }
  }, [actualAttributes['Shock Options'].activeItem]);

  const additionalEvent = (value: any, label: any) => {
    console.log('label32131: ', label);
    console.log('value: ', value);
    if (hasLoaded && label !== 'None') {
      setAttribute('None');
      dispatch(
        SetActiveItem({
          name: 'Lift',
          data: { activeItem: 'None' },
        })
      );
      dispatch(
        SetActiveItem({
          name: nameShock,
          data: { shockActive: 'None', price: 0, shopInfo: { quantity: 1 } },
        })
      );
      dispatch(
        SetActiveItem({
          name: nameWrangler,
          data: { activeItem: 'None' },
        })
      );
      setTimeout(() => {
        setAttribute(value);
        dispatch(
          SetActiveItem({
            name: 'Lift',
            data: { activeItem: value },
          })
        );
      }, 0);
    } else if (hasLoaded && label === 'None') {
      dispatch(
        SetActiveItem({
          name: nameShock,
          data: { shockActive: 'None', price: 0, shopInfo: { quantity: 1 } },
        })
      );
      dispatch(
        SetActiveItem({
          name: nameWrangler,
          data: { activeItem: 'None' },
        })
      );
    }
  };
  useEffect(() => {
    const values = attrShock.values;
    if (values.length !== actualSortAttribute.length) {
      getValidSortValues(values, setActualSortAttribute);
    }
  }, [attrShock.values]);

  return (
    <>
      <div className={s.title}>Lift Height</div>
      <div className={`${productStyle.product__wrapper} ${s.wrapper}`}>
        {attribute.values.map((item: any, index: number) => {
          const data = getProductParameters({
            item,
            attribute,
            setAttribute,
            hintPosition: 'bottom',
            name,
          });

          return (
            <SimpleItem
              {...data}
              additionalEvent={additionalEvent}
              key={`${item.value}-${index}`}
            />
          );
        })}
      </div>
      <div className={s.title}>Wrangler Model</div>
      <div className={s.wrapper}>
        {attrWrangler.values.map((item: any, index: number) => {
          const data = getProductParameters({
            item,
            attribute: attrWrangler,
            setAttribute: setAttrWrangler,
            hintPosition: 'bottom',
            name: nameWrangler,
          });

          return <SimpleItem {...data} key={`${item.value}-${index}`} />;
        })}
      </div>
      <div className={s.title}>Shock Option</div>
      {actualSortAttribute && (
        <div className={s.wrapper}>
          {actualSortAttribute.map((item: any, index: number) => {
            const name = item.label;
            //   const img = item.metadata._img ? pathImage(item.metadata._img) : '';
            const currentValueShock: any = attrShock.value.assetId;

            return (
              <ShockItem
                name={name}
                nameShock={nameShock}
                img={item.metadata._img}
                setAttrShock={setAttrShock}
                attrShock={attrShock}
                item={item}
                onlyNone={wrangler === 'None'}
                currentValueShock={currentValueShock}
              />
            );
          })}
        </div>
      )}
      {allValue['Wrangler Model'] === 'None' && allValue['Lift'] !== 'None' && (
        <div className={s.error}>
          <Error />
          <span>{error.ifWranglerIsNone}</span>
        </div>
      )}

      {allValue['Shock Options'] === 'None' && allValue['Lift'] !== 'None' && (
        <div className={s.error}>
          <Error />
          <span>{error.ifShockIsNone}</span>
        </div>
      )}
    </>
  );
};
