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 { FaSadCry } from 'react-icons/fa'
import ViewPage from '../../../Layout/Dashboard/ViewPage';
import { Rate, 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 { BsInfoCircle } from 'react-icons/bs';
import { useGetOneCoupon, useUpdateCoupon } from '../../../api/Coupon';
import useNavigateOnSuccess from '../../../Hooks/useNavigateOnSuccess';
import Form from './EditForm';

const EditPage = () => {
  const { setObjectToEdit, objectToEdit } = usePageState()
  const { t } = useTranslation();
  const { data,isLoading:IsloadingButton,isRefetching } = useGetOneCoupon()
  const { mutate, isSuccess } = useUpdateCoupon("put")
  const handleSubmit = (values: any) => {
    const products = values?.product_attr?.map((item: any) => {
      const itemableId = typeof item === 'object' ? item.value : item;
      return { "itemable_type": "product", "itemable_id": itemableId };
  })?.filter((item: any) => item.itemable_id !== "") || [];
  
  const category = values?.category_attr?.map((item: any) => {
      const itemableId = typeof item === 'object' ? item.value : item;
      return { "itemable_type": "category", "itemable_id": itemableId };
  })?.filter((item: any) => item.itemable_id !== "") || [];
  
    // Create an object to hold the values to be mutated
    const mutationData: any = {};

    if (values?.name !== null) mutationData["name"] = values.name;
    if (values?.status !== null) mutationData["status"] = values.status ? "active" : "inActive";
    if (values?.minimum_total_to_order !== null) mutationData["minimum_total_to_order"] = values.minimum_total_to_order;
    if (values?.maximum_number_of_uses_per_user !== null) mutationData["maximum_number_of_uses_per_user"] = values.maximum_number_of_uses_per_user;
    if (values?.maximum_number_of_uses !== null) mutationData["maximum_number_of_uses"] = values.maximum_number_of_uses;
    if (values?.coupon_value !== null) mutationData["coupon_value"] = values.coupon_value;
    if (values?.coupon_type !== null) mutationData["coupon_type"] = values.coupon_type;
    if (values?.discount_type !== null) mutationData["discount_type"] = values.discount_type;
    if (values?.active !== null && values?.active.length === 2) {
        mutationData["active_at"] = values.active[0].format('YYYY-MM-DD HH:mm:ss.SSS');
        mutationData["active_to"] = values.active[1].format('YYYY-MM-DD HH:mm:ss.SSS');
    }
    if (products.length > 0 || category.length > 0) {
        mutationData['items'] = [...products, ...category];
    }

    console.log(mutationData,"mutationData");
    
    // Perform the mutation with the constructed mutationData object
    mutate(mutationData);
}


  useNavigateOnSuccess(isSuccess, '/Coupon')


  useEffect(() => {

    setObjectToEdit(data?.coupon);

  }, [data?.coupon]);


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



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


  return (
    <div className='ViewPage'>
      {objectToEdit && data ?
        <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>
        : <LoadingPage />}


    </div>
  )

}

export default EditPage