import React from 'react';
import { useFormikContext } from 'formik';
import { useGetSingleAttribute } from '../../../../../api/attribute';
import { Select } from 'antd';
import { useTranslation } from 'react-i18next';

const Attribute = ({ tabKey }: any) => {
  const { values, setFieldValue } = useFormikContext<any>();
  const language = localStorage.getItem("language") ?? "en";
  const [t] = useTranslation()
  const { data: attributeData } = useGetSingleAttribute({ name: "category_id", id: values?.category_id });


    
  const handleAttributeChange = (value: any, option: any) => {
    // console.log(option[0],"option");
    
    setFieldValue(`variable[${tabKey}].attribute[${option[0].id}]`, option);
    
  };


  return (
    attributeData?.data?.map((item: any) => {
      const uniqueOptionsMap = new Map();
      item?.attribute_value.forEach((attr: any) => {
        if (!uniqueOptionsMap.has(attr.value[language])) {
          uniqueOptionsMap.set(attr.value[language], { attribute_id: attr.id, id: attr.attribute_id });
        }
      });

      const options = Array?.from(uniqueOptionsMap?.entries())?.map(([label, value]) => ({
        label,
        value: value.attribute_id, // Change value to attribute_id
        id: value.id, // Include id in the option
      }));

      if (options.length === 0) {
        return <></>; // Don't render anything if options are empty
      }
    // console.log(options[0].id,"options");
    // console.log(values?.variable[tabKey]?.attribute,"values?.[options[0].id");

      return (
        <div className='ValidationField'>

        <label htmlFor={item?.name[language]} className="text">
        {t(`${item?.name[language]}`)}

        <Select
          placeholder={t(`${item?.name[language]}`)}
            options={options}
            size="large" 
             className={`w-100`}
             
             
             defaultValue={values?.variable?.[tabKey]?.attribute?.[options?.[0]?.id]}
             allowClear
            mode={"multiple" }
            onChange={handleAttributeChange}



          />
        </label>
        </div>
     
         
      );
    })
  );
};

export default Attribute;
