// TabsContainer.tsx
import React, { useEffect, useRef, 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 { MdOutlineDeleteOutline } from 'react-icons/md';

const { TabPane } = Tabs;


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

  const { setFieldValue } = useFormikContext();
  const formikContext = useFormikContext<FormikValues>();
  const { values } = formikContext;
  
  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
  useEffect(() => {
    if (items.length > 0) {
      setActiveKey(items[0].key);
    }
  }, []);
  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(() => {
    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 }]);
    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}` };
      setItems([...items, newItem]);
      setActiveKey(newKey);
  
      const originalValues = values?.Attribute[parentKey].AttributeValue[targetKey];
      setFieldValue(`Attribute[${parentKey}].AttributeValue[${newKey}]`, {...originalValues,id:null});
    }
  };
  
  const [removedAttributeValue, setremovedAttributeValue] = useState<string[]>([]);

  useEffect(() => {
    setFieldValue(`removedAttributeValue[${parentKey}]`, removedAttributeValue);
   
  }, [removedAttributeValue]);

  const handleRemove = (targetKey: string) => {
        
    const newItems = items.filter((item:any) => item?.key !== targetKey);
    console.log(newItems,"newItems",targetKey,"targetKey");
    const removedItem = values?.Attribute[parentKey]?.AttributeValue[targetKey] as any;
    if (removedItem?.id && removedItem?.id !== null &&removedItem?.id !== 0 ) {
      console.log(removedItem?.id,"removedItem?.id");
      setremovedAttributeValue((prevremovedAttributeValue) => [...prevremovedAttributeValue, removedItem.id]);
    }
        const newActiveKey = newItems.length ? newItems[newItems.length - 1].key : '1';
        setItems(newItems);
        setActiveKey(newActiveKey);
        setFieldValue(`Attribute.${parentKey}.AttributeValue.${targetKey}`, undefined);
};


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.map((item :any) =>{
        return  (
        
          <TabPane
            key={item?.key}
            tab={
              <Space>
                {t(`${item.label}`)}
                <CopyOutlined onClick={() => handleDuplicate(item.key)} />
              </Space>
            }
            closable={item.closable}
          >
            <AttributeValueTabs parentKey={parentKey} tabKey={item?.key} />
          </TabPane>
        )
      })}
    </Tabs>
  );
};
