import React, { useEffect, useState } from 'react'
import { getInitialValues, getDataToSend } from '../formUtil'
import { Tab, TabList, TabPanel as TabBody, Tabs } from 'react-tabs'
import 'react-tabs/style/react-tabs.css';
import { MdLanguage } from 'react-icons/md'
import ViewPage from '../../../Layout/Dashboard/ViewPage';
import { usePageState } from '../../../lib/state mangment/LayoutPagestate';
import { useParams } from 'react-router-dom';
import LoadingPage from '../../../Layout/app/LoadingPage';
import { useTranslation } from 'react-i18next';
import { BsInfoCircle } from 'react-icons/bs';
import { useAddProductVariation, useDeleteProductVariation, useGetOneProduct, useUpdateProduct, useUpdateProductVariation } from '../../../api/product';
import { Spin } from 'antd';
import BasicInfo from './BasicInfo';
import { TabsContainer } from './FormikTab/TabsContainer';
import { isvalidation } from './Addfn/isvalidation';
import filterUndefinedAndEmpty from '../../../utils/Array/filterUndefinedAndEmpty';
import useNavigateOnSuccess from '../../../Hooks/useNavigateOnSuccess';

const ViewProduct = () => {
  const { setObjectToEdit, objectToEdit } = usePageState()
  const { t } = useTranslation();
  const { id } = useParams()
  const { data, isLoading, isRefetching } = useGetOneProduct({ id: id })

  const [OldData, setOldData] = useState(data?.data?.products)
  const { mutate, isSuccess, isLoading: IsloadingButton } = useUpdateProduct('put')
  const { mutate: UpdateVariation } = useUpdateProductVariation()
  const { mutate: AddVariation } = useAddProductVariation()


  const { mutate: DeleteVariation } = useDeleteProductVariation()

  const [removedVariant, setremovedVariant] = useState<any[]>([])

  const [Variant, setVariant] = useState<any>([])


  const handleSubmit = (values: any) => {
    // Update removedVarianteValues state
    // console.log(values?.removedVariant, "values?.removedVariant");
    console.log(values?.variable[1], "values");

    function isValid() {
      setremovedVariant(values?.removedVariant);
      const variables = values?.variable?.slice(1);
      if (variables) {
        variables.forEach((item: any, index: number) => {
          setVariant((prevEditAttribute: any) => [...prevEditAttribute, item]);
        })
      };
      const newData = {
        name: {
          en: values?.name_en,
          ar: values?.name_ar,
          de: values?.name_de
        },
        category_id: values?.category_id
      };

      mutate(newData);
    }
    const validationResults = isvalidation(values.variable, t);
    if (validationResults.every((result) => result)) {
      isValid();
    }


  };




  function arraysAreEqual(array1: any, array2: any) {
    // Sort both arrays
    const sortedArray1 = array1.slice().sort();
    const sortedArray2 = array2.slice().sort();

    // Compare the sorted arrays
    return JSON.stringify(sortedArray1) === JSON.stringify(sortedArray2);
  }



  useEffect(() => {
    if (isSuccess) {
      const filtered_Variant = filterUndefinedAndEmpty(Variant);

      // eslint-disable-next-line array-callback-return
      filtered_Variant?.map((dataToSend: any, index: number) => {
        console.log(dataToSend, "dataToSend");
        const varible = dataToSend
        if (varible?.id && varible?.id !== null && varible?.id !== 0) {
          const foundObject = OldData.find((item: any) => item.id === varible?.id) as any;
          const formattedOldInfoData = foundObject?.info ? Object.entries(foundObject?.info).map(([key, value], index) => ({
            [`Description`]: key,
            [`key`]: value,
          })) : [];
          // const info = varible?.info
          const info = varible?.info ?? [];
          const convertedArray = info?.reduce((acc: any, obj: any) => {
            acc[obj.Description] = obj.key;
            return acc;
          }, {});
          const jsonString = Object.keys(convertedArray).length === 0 ? null : JSON.stringify(convertedArray);

          const images_product = foundObject?.images?.map((item: any) => {
            return item?.path
          })
          console.log(varible?.images,"varible?.images");
          
          const array1 = images_product;
          const array2 = varible?.images;
          const Oldimages = isthereequal(array2 || [], foundObject.images || []);
            const finalImageData= removeStrings(array2 || [])
          const isEqual_images = array1.length === array2.length && array1.every((value: any, index: any) => value === array2[index]);
          // const Newimages = varible?.images?.map((item: any) => {
          //   const value = typeof item === 'object' ? item.url : item;
          //   return [value];
          // });

          
          console.log("Arrays are equal:", isEqual_images);
          console.log("finalImageData", finalImageData);
          console.log("Oldimages", Oldimages);
          const filteredOldimages = Oldimages.filter(item => item !== undefined);


          const images = isEqual_images ? {  } : { images:[...finalImageData,...filteredOldimages] }
          


          const Editedproduct = {
            name: {
              en: varible?.name_en,
              ar: varible?.name_ar,
              de: varible?.name_de
            },
            description: {
              en: varible?.description_en,
              ar: varible?.description_ar,
              de: varible?.description_de
            },
            // quantity: varible?.quantity,
            main_photo: varible?.main_photo,
            ...images,
            info: jsonString,
            price: varible?.price,
          

            // product_attributes: varible?.attribute?.map((item: any, index: any) => {
            //   return { attribute_value_id: item?.value, attribute_id: item?.id }
            // }),

          } as any



          if (foundObject) {
            Object.keys(Editedproduct).forEach((propName: any) => {
              if (foundObject.hasOwnProperty(propName)) {
                const foundValue = foundObject[propName];
                //@ts-ignore
                const editedValue = Editedproduct[propName];
                if (foundValue === editedValue) {
                  //@ts-ignore
                  delete Editedproduct[propName];
                }
              }

            });
            if (foundObject.name &&
              foundObject.name.en === Editedproduct.name.en &&
              foundObject.name.ar === Editedproduct.name.ar &&
              foundObject.name.de === Editedproduct.name.de) {
              //@ts-ignore
              delete Editedproduct.name;
            }

            if (foundObject.description &&
              foundObject.description.en === Editedproduct.description.en &&
              foundObject.description.ar === Editedproduct.description.ar &&
              foundObject.description.de === Editedproduct.description.de) {
              //@ts-ignore
              delete Editedproduct.description;
            }

            Object.keys(Editedproduct).forEach((key: any) => {
              // Check if the property value is undefined
              //@ts-ignore

              if (Editedproduct[key] === undefined) {
                // Remove the property
                //@ts-ignore
                delete Editedproduct[key];
              }
            });
            console.log(foundObject.info, "foundObject.info");

            const isEqual = arraysAreEqual(formattedOldInfoData, varible?.info);
            console.log(isEqual, "isEqual");

            if (isEqual) {
              //@ts-ignore
              delete Editedproduct?.info;
            }


            if (Object.keys(Editedproduct).length > 0) {
              //@ts-ignore
              Editedproduct._method = "PUT";
              //@ts-ignore
              Editedproduct.id = foundObject?.id;
              console.log(Editedproduct, "Editedproduct");
              UpdateVariation(Editedproduct)

            }

          }


        } else {
          const info = varible?.info ?? [];
          const convertedArray = info?.reduce((acc: any, obj: any) => {
            acc[obj.Description] = obj.key;
            return acc;
          }, {});
          const jsonString = Object.keys(convertedArray).length === 0 ? null : JSON.stringify(convertedArray);

        
    const StringimagesArray = varible?.images?.filter((item: any) => typeof item === 'string') || [];
    const FileimagesArray = varible?.images?.filter((item: any) => typeof item !== 'string') || [];
    
    console.log(FileimagesArray,"FileimagesArray");
    console.log(StringimagesArray,"StringimagesArray");

    const images = { images: FileimagesArray };

    const main_photo = (typeof varible?.main_photo === 'string') ? {} : { main_photo: varible?.main_photo };
    
    const copied_assets = {
      ...(typeof varible?.main_photo === 'string' ? { main_photo: varible?.main_photo } : {}),
      ...(StringimagesArray.length > 0 ? {images:StringimagesArray} : {})

    }
    const copied_assets_arry = Object.keys(copied_assets).length !== 0 ? { copied_assets: copied_assets } : {};
   
    
    console.log(images,"images");
    console.log(main_photo,"main_photo");
    console.log(copied_assets,"copied_assets");
 


  const mappedAttributes = varible.attribute?.map((item: any) => {
    return item?.map((subitem: any) => ({
        attribute_value_id: subitem?.value,
        attribute_id: subitem?.id
    }));
});

console.log(mappedAttributes, "mappedAttributes");

// Flatten the array of arrays
const flattenedAttributes = mappedAttributes?.filter(Boolean)?.flat();

const arrayOfObjects = flattenedAttributes?.map((subArray: any, index: any) => {
    console.log(subArray, "subArray");
    console.log(index, "index");

    return {
        ...subArray,
    };
});
  

    
          const Newproduct = {
            name: {
              en: varible?.name_en,
              ar: varible?.name_ar,
              de: varible?.name_de
            },
            description: {
              en: varible?.description_en,
              ar: varible?.description_ar,
              de: varible?.description_de
            },
            // quantity: varible?.quantity,

            info: jsonString,
            price: varible?.price,
            base_product_id: id,

            ...images,
      ...main_photo,
      ...copied_assets_arry,


      

      product_attributes: arrayOfObjects,


          }


          AddVariation(Newproduct)
        }

      })

      console.log(removedVariant);
      const filtered_removedVariant = filterUndefinedAndEmpty(removedVariant);
      console.log(filtered_removedVariant);

      removedVariant?.map((item: any) => {
        return DeleteVariation({ id: item })
      })
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isSuccess])



  useNavigateOnSuccess(isSuccess, '/products')


  useEffect(() => {
    // refetch()
    setObjectToEdit(data?.data);
    setOldData(data?.data?.products)
  }, [data, data?.data?.products, data?.data, id, isRefetching, setObjectToEdit]);

  const getValidationSchema = () => {
    return null
  };
  if (isRefetching || isLoading) {
    return <Spin />
  }

  const ViewProps = { getInitialValues, getValidationSchema, getDataToSend, handleSubmit, IsloadingButton };


  return (
    <div className='ViewPage'>
      {objectToEdit && data?.data && objectToEdit ?
        <ViewPage {...ViewProps}>
          <Tabs>
            <TabList>
              <Tab><div className='SignleDriverContainer'><span className='SignleDriverInfoIcon'><MdLanguage size={20} /></span> <h6 className='SingleDriverInfo'>{t("Base_info")}</h6></div></Tab>

              <Tab><div className='SignleDriverContainer'><span className='SignleDriverInfoIcon'><BsInfoCircle size={20} /></span> <h6 className='SingleDriverInfo'>{t("VarianInfo")}</h6></div></Tab>


            </TabList>
            <TabBody >
              <div className=" mt-4"><BasicInfo /></div>
            </TabBody>
            <TabBody >
              <div className=" mt-4"> {isLoading && objectToEdit && isRefetching ? <Spin /> : <TabsContainer />} </div>
            </TabBody>

          </Tabs>
        </ViewPage>
        : <LoadingPage />}


    </div>
  )

}

export default ViewProduct



function isthereequal(arr1: any[], arr2: any[]): any[] {
  console.log("arr1:", arr1);
  console.log("arr2:", arr2);

  const equalItems = arr2
    .filter(item2 => arr1.some(item1 => item1 === item2?.path))
    .map(item => item.id);

  console.log("Equal items found in arr2:", equalItems);

  return equalItems;
}

function removeDuplicates(arr1: any[], arr2: any[]): any[] {
  const combinedArray = [...arr1, ...arr2];
  const uniqueArray = combinedArray.filter((item, index) => {
    return combinedArray.indexOf(item) === index;
  });
  return uniqueArray;
}

function removeStrings(arr: any[]): any[] {
  return arr.filter(item => typeof item !== 'string');
}
