import React, { useEffect, useState } from 'react'
import { getInitialValuesForAdd as getInitialValues, getValidationSchema, 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 { useTranslation } from 'react-i18next';
import useNavigateOnSuccess from '../../../Hooks/useNavigateOnSuccess';
import { useAddCoupon } from '../../../api/Coupon';
import Form from './AddForm';

const AddCouponPage = () => {


  const { mutate, isLoading:IsloadingButton, isSuccess } = useAddCoupon()
  const handleSubmit = (values: any) => {
    const transformedValues = { ...values }; // Create a new object
    
    // Apply transformations
    transformedValues.active_at = values.active[0]?.format('YYYY-MM-DD HH:mm:ss.SSS') || '';
    transformedValues.active_to = values.active[1]?.format('YYYY-MM-DD HH:mm:ss.SSS') || '';
    transformedValues.status = values.active ? "active" : "inActive";
  
    const products = Array.isArray(values?.product_attr) ? 
      values.product_attr
        .map((item: any) => ({ "itemable_type": "product", "itemable_id": item }))
        .filter((item: any) => item.itemable_id !== "") || [] : [];
  
    const category = Array.isArray(values?.category_attr) ? 
      values.category_attr
        .map((item: any) => ({ "itemable_type": "category", "itemable_id": item }))
        .filter((item: any) => item.itemable_id !== "") || [] : [];
  
    if (products.length > 0 || category.length > 0) {
      transformedValues['items'] = [...products, ...category];
    }
  
    console.log(transformedValues, "transformedValues");
    mutate(transformedValues);
  };
  

  const { t } = useTranslation();

  useNavigateOnSuccess(isSuccess, '/Coupon')



  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>



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

        </Tabs>
      </ViewPage>



    </div>
  )

}

export default AddCouponPage