// 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 { useProductVarianState } from '../../../../lib/state mangment/Pages/Products';
import { VariableTabs } from './VariableTabs';
import { log } from 'console';
import { MdOutlineDeleteOutline } from 'react-icons/md';

const { TabPane } = Tabs;


export const TabsContainer: React.FC = () => {
  const [activeKey, setActiveKey] = useState('1');
  const [t] = useTranslation()
  const initialItemShape: any = {
    label: `${t(`variant`)} 1`,
    key: '1',
    closable: true,
  };
  const formikContext = useFormikContext<FormikValues>();
  const { setFieldValue } = useFormikContext();
  const { values, handleChange } = formikContext;
  const varianCount = values?.variable?.slice(1)?.map((item: any, index: any) => {
    return {
      label: `${t(`variant`)}` + `${index + 1}`,
      key: index + 1,
      closable: true,
    }
  }) ?? initialItemShape
  const [items, setItems] = useState(varianCount ?? [initialItemShape]); // Ensure items is always an array
  const [width, setWidth] = useState(window.innerWidth);

  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(`variant`)} ${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(`variant`)} ${newKey}` };
      setItems([...items, newItem]);
      setActiveKey(newKey);

      const originalValues = values?.variable?.[targetKey];
        console.log(originalValues?.id,'originalValues?.id');
        
      if(originalValues?.id === null){
        console.log(originalValues?.id,'`1`');

        setFieldValue(`variable.${newKey}`, { ...originalValues, id: 0 });

      }else{
        console.log(originalValues?.id,'2');

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

      }

      const originalInfo = values?.info?.[targetKey];

      setFieldValue(`info.${newKey}`, originalInfo);

      const originalvariable = values?.variable[targetKey]?.variable;

      setFieldValue(`variable.${newKey}.variable`, originalvariable);

    }
  };

  const [removedVariant, setremovedVariant] = useState<string[]>([]);
  useEffect(() => {
    setFieldValue(`removedVariant`, removedVariant);

  }, [removedVariant]);
  const handleRemove = (targetKey: string) => {
    const newItems = items.filter((item: any) => item.key !== targetKey);
    const removedItem = values?.variable[targetKey] as any;
    if (removedItem?.id) {
      setremovedVariant((prevRemovedvariable) => [...prevRemovedvariable, removedItem.id]);
    }
    const newActiveKey = newItems.length ? newItems[newItems.length - 1].key : '1';
    setItems(newItems);
    setActiveKey(newActiveKey);
    setFieldValue(`variable.${targetKey}`, undefined);
    setFieldValue(`info.${targetKey}`, undefined);


  };

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

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  const tabPosition = width > 1000 ? 'left' : '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: <VariableTabs tabKey={item.key} />,
            key: item.key,
            closable: item.closable,
          }))
        }

      >

      </Tabs>
      {items.length === 0 && (
        <h6 className='AddNewTabText'>{t("Add New Variant")}</h6>

      )}
    </>
  );
};
