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 { Spin } from 'antd';
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 { useGetOneCategories, useUpdateCategories } from '../../../api/Categories';
import useNavigateOnSuccess from '../../../Hooks/useNavigateOnSuccess';
import { TabsContainer } from './Add/AttributeTab/TabsContainer';
import { useAddAttribute, useGetSingleAttribute } from '../../../api/attribute';
import { useDeleteAttribute, useUpdateAttribute } from '../../../api/attribute';
import { useAddAttributeValue, useDeleteAttributeValue, useUpdateAttributeValue } from '../../../api/attributeValue';
import { toast } from 'react-toastify';
import Form from './Add/AddForm';
import filterUndefinedAndEmpty from '../../../utils/Array/filterUndefinedAndEmpty';

const EditPage = () => {
  const { setObjectToEdit, objectToEdit } = usePageState()
  const { t } = useTranslation();
  const { data, isLoading, isRefetching } = useGetOneCategories()
  const { id } = useParams()

  const { data: Atrribute, isLoading: isLoadingAtrribute, isRefetching: AttributeisRefetching } = useGetSingleAttribute({ name: "category_id", id: id }, {})
  const { mutate, isSuccess,isLoading:IsloadingButton } = useUpdateCategories()
  const { mutateAsync } = useAddAttribute()
  const { mutate: mutateAttributeValue } = useAddAttributeValue()
  const { mutate: UpdateAttribute } = useUpdateAttribute("put")
  const { mutate: UpdateAttributeValue } = useUpdateAttributeValue()
  const { mutate: DeleteAttributeValue } = useDeleteAttributeValue()
  const { mutate: DeleteAttribute } = useDeleteAttribute()


  const [removedAttribute, setremovedAttribute] = useState<any[]>([])
  const [removedAttributeValue, setremovedAttributeValue] = useState<any[]>([])



  const [AddAttribute, setAddAttribute] = useState<any[]>([])
  const [EditAttribute, setEditAttribute] = useState<any[]>([])

  const [AddAttributeValue, setAddAttributeValue] = useState<any[]>([])
  const [EditAttributeValue, setEditAttributeValue] = useState<any[]>([])
  const [OldData, setOldData] = useState(Atrribute?.data)
  const [OldDataValues, setOldDataValues] = useState([])


  const handleSubmit = (values: any) => {

    function isValid() {
      const attributes = values?.Attribute?.slice(1);
      const flattenedAndFiltered = values?.removedAttributeValue?.flat().filter((value:any) => value !== undefined);

      console.log(flattenedAndFiltered,"flattenedAndFiltered");

      setremovedAttribute(values?.removedAttribute)
      setremovedAttributeValue(flattenedAndFiltered)
      
      if (attributes) {
        attributes.forEach((item: any, index: number) => {
          if (item?.id && item?.id !== null) {
            console.log(item,"setEditAttribute");
          
            setEditAttribute((prevEditAttribute) => [...prevEditAttribute, item]);
            if (item?.AttributeValue) {
              item.AttributeValue.slice(1).forEach((attrValueItem: any) => {
                if (attrValueItem && Object.keys(attrValueItem).length > 0) { // Check if attrValueItem is defined and not empty
                  setEditAttributeValue((prevEditAttributeValue) => [...prevEditAttributeValue, [index, attrValueItem]]);
                  console.log(attrValueItem,"setEditAttributeValue");

                }
              });
            }
          } else {
            setAddAttribute((prevAddAttribute) => [...prevAddAttribute, item]);
            console.log(item,"setAddAttribute");

            if (item?.AttributeValue) {
              item?.AttributeValue?.slice(1)?.forEach((attrValueItem: any) => {                
                if (attrValueItem && Object.keys(attrValueItem)?.length > 0) { // Check if attrValueItem is defined and not empty
                  console.log(attrValueItem,"setAddAttributeValue");

                  setAddAttributeValue((prevEditAttributeValue) => [...prevEditAttributeValue, [index, attrValueItem]]);
                }
              });
            }
          }
        });
      }

      const EditedCategory = {
        name: {
          en: values?.name_en,
          ar: values?.name_ar,
          de: values?.name_de
        },
        photo: values?.photo,
        parent_id: values?.parent_id,
        _method: "PUT"
      }

      const Imagetype = typeof values?.photo
      if (Imagetype === "string") {
        delete EditedCategory['photo']
      }

      
      mutate(EditedCategory)
    }
    const validationResults: boolean[] = [];
      let previousNames: any = {};
      
      values?.Attribute?.slice(1)?.forEach((item: any, index: any) => {
      if (item && Object.keys(item).length > 0) {
      const itemName = t('name');
      const itemNumber = index + 1;
      
      // Check if the names are unique across items
      const currentItemNames = {
      name_ar: item?.name_ar,
      name_en: item?.name_en,
      name_de: item?.name_de,
      };
      
      if (
      previousNames.name_ar === currentItemNames.name_ar ||
      previousNames.name_en === currentItemNames.name_en ||
      previousNames.name_de === currentItemNames.name_de
      ) {
      toast.error(`${itemName} ${t('unique_error_names')}`);
      validationResults.push(false);
      }
      
      previousNames = currentItemNames;
      
      // Check for other validation rules
      if (!item?.name_ar || !item?.name_en || !item?.name_de) {
      toast.error(`${t('required_name')} ${itemNumber}`);
      validationResults.push(false);
      } else if (!item?.type) {
      toast.error(`${t('required_type')} ${itemNumber}`);
      validationResults.push(false);
      } else if (item?.type === "image") {
      if (Array.isArray(item.AttributeValue)) {
      item?.AttributeValue.slice(1)?.forEach((attrItem: any, index: number) => {
      if (attrItem && Object.keys(attrItem).length > 0) {
      if (attrItem.image === null) {
      toast.error(`${t('required_image')} ${index + 1}`);
      validationResults.push(false);
      } else if (!attrItem?.value_ar || !attrItem?.value_en || !attrItem?.value_de) {
      toast.error(`${t('required_text')} ${index + 1}`);
      validationResults.push(false);
      } else {
      validationResults.push(true);
      }
      }
      });
      }
      } else if (item?.type === "color") {
      if (Array.isArray(item.AttributeValue)) {
      item?.AttributeValue.slice(1)?.forEach((attrItem: any, index: number) => {
      if (attrItem && Object.keys(attrItem).length > 0) {
      const hexColorRegex = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
      if (attrItem && !hexColorRegex.test(attrItem?.value_en)) {
      toast.error(`${t('required_color')} ${index + 1}`);
      validationResults.push(false);
      } else {
      validationResults.push(true);
      }
      }
      });
      }
      } else if (item?.type === "text") {
      if (Array.isArray(item.AttributeValue)) {
      item?.AttributeValue.slice(1)?.forEach((attrItem: any, index: number) => {
      if (attrItem && Object.keys(attrItem).length > 0) {
      if (attrItem && (!attrItem?.value_ar || !attrItem?.value_en || !attrItem?.value_de)) {
      toast.error(` ${t('required_text')} ${index + 1}`);
      validationResults.push(false);
      } else {
      validationResults.push(true);
      }
      }
      });
      }
      } else {
      validationResults.push(true);
      }
      }
      });
      
      if (validationResults.every((result) => result)) {
      isValid();
      }


  }



  function filterByIndex(number: number, array: [number, any][]): any[] {
    return array.filter(([index, _]) => index === number).map(([_, item]) => item);
  }


  useEffect(() => {

    if (isSuccess) {


      const categoryId = id;
      console.log(EditAttribute, "EditAttribute");
      const filteredEditAttribute = filterUndefinedAndEmpty(EditAttribute);

      filteredEditAttribute?.map((dataToSend: any, index: number) => {


        const EditAttribute = dataToSend
        const foundObject = OldData.find((item: any) => item.id === EditAttribute?.id) as any;

        const UpdatedAttribute = {
          name: {
            en: EditAttribute?.name_en,
            ar: EditAttribute?.name_ar,
            de: EditAttribute?.name_de
          },
          type: EditAttribute?.type,
          // category_id:categoryId,


        }
        if (foundObject) {
          Object.keys(UpdatedAttribute).forEach((propName: any) => {
            if (foundObject.hasOwnProperty(propName)) {
              const foundValue = foundObject[propName];
              //@ts-ignore
              const editedValue = UpdatedAttribute[propName];
              if (foundValue === editedValue) {
                //@ts-ignore
                delete UpdatedAttribute[propName];
              }
            }
          })
          if (foundObject.name &&
            foundObject.name.en === UpdatedAttribute.name.en &&
            foundObject.name.ar === UpdatedAttribute.name.ar &&
            foundObject.name.de === UpdatedAttribute.name.de) {
            //@ts-ignore
            delete UpdatedAttribute.name;
          }
          Object.keys(UpdatedAttribute).forEach((key: any) => {
            //@ts-ignore
            if (UpdatedAttribute[key] === undefined) {
              //@ts-ignore
              delete UpdatedAttribute[key];
            }
          });
          if (Object.keys(UpdatedAttribute).length > 0) {
            //@ts-ignore
            // UpdatedAttribute._method = "PUT";
            //@ts-ignore
            UpdatedAttribute.id = foundObject?.id;
            console.log(UpdatedAttribute, "EditAttribute");
            UpdateAttribute(UpdatedAttribute)

          }

        }
        const result: [number, any][] = filterByIndex(index, EditAttributeValue);
        const filteredresult = filterUndefinedAndEmpty(result);
        console.log(filteredresult, "EditAttributeValue");

        filteredresult?.map((dataToSend: any) => {
          if (dataToSend?.id && dataToSend.id !== null) {

            const foundObjectValue = (OldDataValues[index] as any).find((item: any) => item.id === dataToSend?.id) as any;

            const EditAttributeValue = dataToSend
            console.log(EditAttributeValue);

     

            const NewEditAttributeValue = {
              id: EditAttributeValue?.id,
              value: {
                en: EditAttributeValue?.value_en,
                ar: EditAttributeValue?.value_ar ?? EditAttributeValue?.value_en,
                de: EditAttributeValue?.value_de ?? EditAttributeValue?.value_en
              },
              image: EditAttributeValue?.image,
              // attribute_id:EditAttribute?.id,
              // id: EditAttributeValue?.id,
            }

            if (EditAttribute.type === "color") {
              NewEditAttributeValue["value"] = {
                en: EditAttributeValue?.value_en,
                ar: EditAttributeValue?.value_en,
                de: EditAttributeValue?.value_en
              }
            }
            if (EditAttributeValue?.main_photo === "string") {
              delete NewEditAttributeValue['image']
            }

              
            if (foundObjectValue) {

              Object.keys(NewEditAttributeValue).forEach((propName: any) => {
                if (foundObjectValue.hasOwnProperty(propName)) {
                  const foundValue = foundObjectValue[propName];
                  //@ts-ignore
                  const editedValue = NewEditAttributeValue[propName];
                  if (foundValue === editedValue) {
                    //@ts-ignore
                    delete NewEditAttributeValue[propName];
                  }
                }
              })
              Object.keys(NewEditAttributeValue).forEach((key: any) => {
                //@ts-ignore
                if (NewEditAttributeValue[key] === undefined) {
                  //@ts-ignore
                  delete NewEditAttributeValue[key];
                }
              });
              if (foundObjectValue.value &&
                foundObjectValue.value.en === NewEditAttributeValue.value.en &&
                foundObjectValue.value.ar === NewEditAttributeValue.value.ar &&
                foundObjectValue.value.de === NewEditAttributeValue.value.de) {
                //@ts-ignore
                delete NewEditAttributeValue.value;
              }

              if (Object.keys(NewEditAttributeValue).length > 0) {
                //@ts-ignore
                NewEditAttributeValue._method = "PUT";
                //@ts-ignore
                NewEditAttributeValue.id = foundObjectValue?.id;


                UpdateAttributeValue(NewEditAttributeValue)

              }
            }



          }
          else {

            const EditAttributeValue = dataToSend
            // const IMage =
            // (typeof EditAttributeValue?.image === 'string') ?
            // {
            //   copied_image: EditAttributeValue?.image
            // } :
            // {
            //   image: EditAttributeValue?.image
            // };
            const NewEditAttributeValue = {

              value: {
                en: EditAttributeValue?.value_en,
                ar: EditAttributeValue?.value_ar,
                de: EditAttributeValue?.value_de
              },
             image:EditAttributeValue?.image,
              attribute_id: EditAttribute?.id,
            }
            if (EditAttribute.type === "color") {
              NewEditAttributeValue["value"] = {
                en: EditAttributeValue?.value_en,
                ar: EditAttributeValue?.value_en,
                de: EditAttributeValue?.value_en
              }
            }
            mutateAttributeValue(NewEditAttributeValue)
          }



        })

      }

      )
      console.log(removedAttribute, "removedAttribute");
      removedAttribute?.map((item: any) => {
        DeleteAttribute({ id: item })
      })

      const filteredAddAttribute = filterUndefinedAndEmpty(AddAttribute);
      console.log(filteredAddAttribute,"AddAttribute");

      filteredAddAttribute?.map((dataToSend: any, index: number) => {

        const AddAttribute = dataToSend

        const NewAddAttribute = {
          name: {
            en: AddAttribute?.name_en,
            ar: AddAttribute?.name_ar,
            de: AddAttribute?.name_de
          },
          type: AddAttribute?.type,
          category_id: categoryId,
        }

        mutateAsync(NewAddAttribute).then((data: any) => {
          const AttributeId = (data as any)?.id;
          // console.log(AttributeValues[0]?.slice(1),"AttributeValues");
          const result: [number, any][] = filterByIndex(index, AddAttributeValue);
          console.log(AddAttribute?.AttributeValue,"AddAttribute?.AttributeValue");

          AddAttribute?.AttributeValue?.slice(1)?.map((dataToSend: any, index: number) => {

            const AddAttributeValue = dataToSend
            // const IMage =
            // (typeof AddAttributeValue?.image === 'string') ?
            // {
            //   copied_image: AddAttributeValue?.image
            // } :
            // {
            //   image: AddAttributeValue?.image
            // };
            const NewAddAttributeValue = {
              value: {
                en: AddAttributeValue?.value_en,
                ar: AddAttributeValue?.value_ar ?? AddAttributeValue?.value_en,
                de: AddAttributeValue?.value_de ?? AddAttributeValue?.value_en
              },
              image:AddAttributeValue?.image,
              attribute_id: AttributeId,
            }
            mutateAttributeValue(NewAddAttributeValue)

          })
        })

      })
      console.log(removedAttributeValue, "removedAttributeValue");
      removedAttributeValue?.map((item: any) => {
        console.log(item, "item");
        return DeleteAttributeValue({ id: item })
      })



    }
  

  }, [isSuccess])







  useNavigateOnSuccess(isSuccess, '/categories')












  useEffect(() => {

    setObjectToEdit([data?.category, Atrribute?.data]);
    setOldData(Atrribute?.data)

    setOldDataValues(Atrribute?.data?.map((item: any) => {
      return item?.attribute_value
    }))

  }, [data?.category, Atrribute?.data, isRefetching, AttributeisRefetching, setObjectToEdit,isLoadingAtrribute]);


  const getValidationSchema = () => {
    return null
  };


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

  if (AttributeisRefetching || isRefetching || isLoadingAtrribute || isLoading || !objectToEdit || (Array.isArray(objectToEdit) && objectToEdit.some(item => item === undefined))) {
    return <Spin />
  }

  

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

            </TabList>

            <TabBody >
              <div className=" mt-4"><Form /></div>
            </TabBody>

            <TabBody >
              {Atrribute?.data && 
                           <div className=" mt-4"><TabsContainer /></div>
 
              }
            </TabBody>

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


    </div>
  )

}

export default EditPage