import { useAttribute } from '@threekit-tools/treble/dist';
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useStoreDispatch, useStoreSelector } from '../../../App';
import { SetActiveItem } from '../../../store/actions/Settings';
import { getConfigInfo } from '../../../store/selectors/selectors';
import { AttributesT } from '../../../utils/constants';
import { ColorItem } from '../../ColorItem/ColorItem';
import { getActualTitle } from '../Product';
import s from './PaintColor.module.scss';

export const PaintColor = ({ ...props }) => {
  const name: AttributesT = props.name;
  const [attribute, setAttribute]: any = useAttribute(name);

  const dispatch = useStoreDispatch();
  function changeItem(value: any, label: string) {
    let actualDataItem = attribute.values.find(
      (item: any) => item.label === label
    );

    setAttribute(value);
    dispatch(SetActiveItem({ name, data: { activeItem: label } }));
  }

  const search = useLocation().search;

  const attributeInfoCustom = useStoreSelector(getConfigInfo).attributeIsActive;
  let attributeIsActive = attributeInfoCustom && attributeInfoCustom[name];

  useEffect(() => {
    if (!attributeIsActive) {
      dispatch(
        SetActiveItem({ name, data: { activeItem: getActualTitle(attribute) } })
      );
    }
  }, []);
  return (
    <div className={s.wrapper}>
      {attribute.values.map((item: any, index: number) => {
        const bg = item.metadata._bg;
        let isUrlLoaderActive;
        let actualValue;
        if (attribute.value.query && attributeIsActive) {
          actualValue = attribute.value.query.metadata.option;
          isUrlLoaderActive = true;
        } else {
          actualValue = attribute.value.assetId;
          isUrlLoaderActive = false;
        }
        const data = {
          bg,
          name,
          item,
          changeItem,
          currentValue: actualValue,
          isUrlLoaderActive,
        };
        return <ColorItem {...data} key={`${item.value}-${index}`} />;
      })}
    </div>
  );
};
