import React, { useEffect, useState } from 'react'
import {  getValidationSchema, getDataToSend ,getInitialValuesForAdd as getInitialValues} 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 { useTranslation } from 'react-i18next';
import { useAddCategories } from '../../../api/Categories';
import Form from './Add/AddForm';
import { usePageState } from '../../../lib/state mangment/LayoutPagestate';
import { useAddAttribute } from '../../../api/attribute';
import { TabsContainer } from './Add/AttributeTab/TabsContainer';
import { useAddAttributeValue } from '../../../api/attributeValue';

import useNavigateOnSuccess from '../../../Hooks/useNavigateOnSuccess';
import { toast } from 'react-toastify';

const AddcategoriesPage = () => {
    
  const { setObjectToEdit, objectToEdit } = usePageState()

    const {mutate,isLoading:IsloadingButton ,isSuccess,data } = useAddCategories()
    const {mutateAsync} = useAddAttribute()
    const {mutate:AddAttributeValue } = useAddAttributeValue()

    const [Attribute , setAttribute] = useState<any[]>([])
    const [AttributeValues , setAttributeValues] = useState<any[]>([])
 
  
    const handleSubmit = (values:any)=>{ 
      console.log(values,"values");
      function isValid(){
      values?.Attribute?.slice(1)?.forEach((item:any) => {
      if (item && Object.keys(item).length > 0){
      setAttribute((prevAddAttributeValue) => [...prevAddAttributeValue, item]);
      }
      
      });
      
      
      setAttributeValues(values?.Attribute?.slice(1)?.map((item:any)=>{
      if (item && Object.keys(item).length > 0){
      return item?.AttributeValue
      }
      }))
      const CategoriesValues = {
      name: {
      en:values?.name_en,
      ar:values?.name_ar,
      de:values?.name_de
      },
      parent_id:values?.parent_id,
      photo:values?.photo,
      }
      mutate(CategoriesValues) 
      }
      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();
      }
      
     
      
      }
  useEffect(()=>{

    if(isSuccess){
      const categoryId = (data as any )?.id ;

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

        const Attribute = dataToSend 
   
        const NewAttribute = {
          name:{
            en:Attribute?.name_en,
            ar:Attribute?.name_ar,
            de:Attribute?.name_de
          },
          type:Attribute?.type, 
          category_id:categoryId,
        }
      
        mutateAsync(NewAttribute).then((data)=>{
          const AttributeId = (data as any )?.id ;
            console.log(AttributeValues[0]?.slice(1),"AttributeValues");
          AttributeValues[index]?.slice(1)?.map((dataToSend:any , index:number)=>{
    
            const AttributeValue = dataToSend 
            const IMage =
            (typeof AttributeValue?.image === 'string') ?
            {
              copied_image: AttributeValue?.image
            } :
            {
              image: AttributeValue?.image
            };
            const NewAttributeValues = {
              value:{
                en:AttributeValue?.value_en,
                ar:AttributeValue?.value_ar,
                de:AttributeValue?.value_de
              },
              ...IMage,
              attribute_id:AttributeId,
            }
            if (NewAttribute.type === "color") {
              NewAttributeValues["value"] = {
                en: AttributeValue?.value_en,
                ar: AttributeValue?.value_en,
                de: AttributeValue?.value_en
              }
            }
          
            AddAttributeValue(NewAttributeValues)
    
          })
        })  
      })
    
    }

    if(isSuccess){
      setObjectToEdit([]);
    }
  },[isSuccess])


  const {t} = useTranslation();

  useNavigateOnSuccess(isSuccess , '/categories'  )
  
  useEffect(() => {
    
    setObjectToEdit([]);
     
  }, []);

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


  return (
    <div className='ViewPage'>
  
        <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 >
              <div className=" mt-4"><TabsContainer /></div>
            </TabBody>
           
          </Tabs>
        </ViewPage>
        


    </div>
  )

}

export default AddcategoriesPage

