// TabsContainer.tsx
import React, { useEffect, useState } from 'react';
import { Tabs, Space } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import { toast } from 'react-toastify';
import { FormikValues, useFormikContext } from 'formik';
import { useTranslation } from 'react-i18next';
import { AttributeValueTabs } from './AttributeTabs';

import { AttributeValueTabs as AddAttributeValueTabs } from '../../Add/AttributeValueTab/AttributeTabs';
import { MdOutlineDeleteOutline } from 'react-icons/md';

export const TabsContainer = ({ parentKey }: any) => {
  const [activeKey, setActiveKey] = useState('1');
  const [t] = useTranslation()

  const { setFieldValue } = useFormikContext();
  const formikContext = useFormikContext<FormikValues>();
  const { values, handleChange } = formikContext;
  const [width, setWidth] = useState(window.innerWidth);

  
const initialItemShape: any = {
  label:  `${t(`Value`)} 1`,
  key: '1',
  closable: true,
};
  const varianCount = values?.Attribute[parentKey]?.AttributeValue?.slice(1)?.map((item: any, index: any) => {
    return {
      label: `${t(`Value`)}` + `${index + 1}`,
      key: index + 1,
      closable: true,
    }
  }) ?? initialItemShape

  const [items, setItems] = useState(Array.isArray(varianCount) ? varianCount : [initialItemShape]); // Ensure items is always an array
  const findFirstMissingKey = (itemKeys:string[]) => {
    const keysAsNumbers = itemKeys.map(Number); // Convert strings to numbers
    for (let i = 1; i <= keysAsNumbers.length + 1; i++) {
      if (!keysAsNumbers.includes(i)) {
        return i;
      }
    }
  };
  const [nextKey, setNextKey] = useState<any>(items.map((item: any) => `${item.key}`)); // Initialize the key counter to the length of items + 1
  useEffect(() => {
    // Set the active key to the first tab key when the component mounts or items change
    if (items.length > 0) {
      setActiveKey(items[0].key);
    }
  }, []);

  useEffect(() => {
    const keys = items.map((item: any) => `${item.key}`);
    setNextKey(findFirstMissingKey(keys))

  }, [items]);
  const handleAdd = () => {
    const newKey = `${nextKey}`;
    setItems([...items, { key: newKey, label: `${t(`Value`)} ${newKey}`, closable: true,Add:true }]);
    setActiveKey(newKey);

  };

  const handleDuplicate = (targetKey: string) => {
    const targetItem = items.find((item: any) => item.key === targetKey);
    if (targetItem) {
      const newKey = `${nextKey}`;
      const newItem = { ...targetItem, key: newKey, label: `${t(`Value`)} ${newKey}`,Add:true };
      setItems([...items, newItem]);
      setActiveKey(newKey);
      setNextKey((prevKey : any) => prevKey + 1);


      const originalValues = values?.Attribute?.[parentKey]?.AttributeValue?.[targetKey];
  
      setFieldValue(`Attribute.${parentKey}.AttributeValue.${newKey}`,  {...originalValues,id:null});
        console.log({...originalValues,id:null},"{...originalValues,id:null}");
        
    }
  };

  const [removedAttributeValues, setRemovedAttributeValues] = useState<string[]>([]);
  useEffect(() => {
    setFieldValue(`removedAttributeValue[${parentKey}]`, removedAttributeValues);

  }, [removedAttributeValues]);

  const handleRemove = (targetKey: string) => {
    const newItems = items?.filter((item: any) => item.key !== targetKey) as any;
    const removedItem = values?.Attribute?.[parentKey]?.AttributeValue?.[targetKey] as any;
    console.log(removedItem?.id,"attrrubute value?.id");
    
    if (removedItem?.id && removedItem?.id !== null &&removedItem?.id !== 0 ) {
      setRemovedAttributeValues((prevRemovedAttributeValues) => [...prevRemovedAttributeValues, removedItem.id]);
    }

    const newActiveKey = newItems.length ? newItems[newItems.length - 1].key : '1';
    setItems(newItems);
    setActiveKey(newActiveKey);
    setFieldValue(`Attribute.${parentKey}.AttributeValue.${targetKey}`, undefined);
    
  };

  useEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  const tabPosition = 'top';

  return (
  <>
    <Tabs
      type="editable-card"
      onChange={setActiveKey}
      activeKey={activeKey}
      onEdit={(targetKey: any, action) => (action === 'add' ? handleAdd() : handleRemove(targetKey))}
      tabPosition={tabPosition}
      removeIcon={<MdOutlineDeleteOutline size={20}/>}

      items={
      items.map((item: any) => ({
        label: <Space>{t(`${item.label}`)} <CopyOutlined onClick={() => handleDuplicate(item.key)} /></Space>,
        // children: item?.Add  ?  <AddAttributeValueTabs  parentKey={parentKey} tabKey={item.key} /> : <AttributeValueTabs  parentKey={parentKey} tabKey={item.key} />,
        children: <AddAttributeValueTabs  parentKey={parentKey} tabKey={item.key} /> ,

        key: item.key,
        closable: item.closable,
      })) 
    }

    >
      
    </Tabs>
   { items.length === 0 && (
            <h6>{t("Add_New_value")}</h6>
         )}
  </>
  );
};
