// TabsContainer.tsx
import React, { useEffect, useState } from 'react';
import { Tabs, Space } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import {  FormikValues, useFormikContext } from 'formik';
import { useTranslation } from 'react-i18next';
import { AttributeTabs  as AddAttributeTabs} from '../../Add/AttributeTab/AttributeTabs';
import { MdOutlineDeleteOutline } from 'react-icons/md';


export const TabsContainer: React.FC = () => {
  const [activeKey, setActiveKey] = useState('1');
  const { setFieldValue } = useFormikContext();
  const formikContext = useFormikContext<FormikValues>();
  const { values } = formikContext;
  const [width, setWidth] = useState(window.innerWidth);  
  const [t] = useTranslation()

  
const initialItemShape: any = {
  label:  `${t(`Attribute`)} 1`,
  key: '1',
  closable: true,
};
 

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

  const [items, setItems] = useState(varianCount ?? [initialItemShape]); // Ensure items is always an array
  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);
    }
  }, []);
  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(`Attribute`)} ${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(`Attribute`)} ${newKey}`,Add:true };
      setItems([...items, newItem]);
      setActiveKey(newKey);
      setNextKey((prevKey : any) => prevKey + 1);

  
      const originalValues = values?.Attribute?.[targetKey];

        setFieldValue(`Attribute.${newKey}`, {...originalValues,id:null});

    }
  };
  const [removedAttribute, setRemovedAttribute] = useState<string[]>([]);
  useEffect(() => {
    setFieldValue(`removedAttribute`, removedAttribute);

  }, [removedAttribute]);


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


    
};

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

  window.addEventListener('resize', handleResize);

  return () => {
      window.removeEventListener('resize', handleResize);
  };
}, []);
const tabPosition = width > 1000 ? 'left' : 'top';

  return (
<div className=''>
 
<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:  <AddAttributeTabs  tabKey={item.key}/>,

       key: item.key,
       closable: item.closable,
     }))}
   >
   </Tabs>
     { items.length === 0 && (
      <h6 className='AddNewTabText'>{t("Add New Attribute")}</h6>
   )}
</div>
  );
};
