import React, { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Form, Space } from 'antd';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { InputField } from '../../Components/Forms/InputField';
import { DropDowns } from '../../Components/Forms/DropDown';
import { DefaultModal } from '../../Components/Modal/DefaultModal';
import Buttons from '../../Components/Forms/Buttons';
import { Tables } from '../../Components/Tables/Table';
import { Messages } from '../../Components/Notifications/Messages';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import Imageupload from '../../Components/Forms/Upload.jsx';
import { Search } from '../../Components/Forms/Search';
import FormHeader from '../PageComponents/FormHeader.jsx';
import ConfigExcel from './ConfigExcelUpload.jsx';
import {
  configDataSelector,
  getConfiguration,
  getConfigTypeData,
  deleteConfiguration,
  postConfiguration,
  putConfiguration,
  postBulkConfiguration,
  postbulkconfigdata,
} from '../../Features/ConfigMasterPage/ConfigMasterPage.js';
import {
  configTypeActiveDataSelector,
  getActiveConfigTypeNames,
} from '../../Features/ConfigTypePage/ConfigTypePage.js';
import { emptyExcelData } from '../../Features/ExcelUploadPage/ExcelUploadPage.js';
import { getSession, validateSafeInput } from '../../Services/Others';
import TertiaryButton from '../../Components/Forms/tertiaryButton.jsx';
import '../../Components/Forms/main.scss';
import '../../Styles/OverAllStyle/OverAllStyle.scss';
import {
  getAllsubcatdata,
  getProdCatData,
} from '../../Features/ProductPage/ProductPage.js';
import { useAuth } from '../../AuthContext.jsx';

const subDirectory = import.meta.env.BASE_URL;
const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },
];

const CommonMaster = () => {
  const { SadminuserAccess } = useAuth();

  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Common Master'
  );

  const dispatch = useDispatch();
  const [form] = Form.useForm();

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const AppType = getSession('AppType');

  const CommonData = useSelector(configDataSelector);
  const ConfigTypeNames = useSelector(configTypeActiveDataSelector);
  const baseConfigTypeOptions = [
    'Wholesale Extra Charges',
    'Wholesale Unit Of Measure',
    'Wholesale Quantity',
    'Wholesale Screen Name',
    'Wholesale Payment Mode',
    'Wholesale Designation',
  ];

  const configTypeOptions =
    UserType === 'Super Admin' || UserType === 'Super Admin User'
      ? [...baseConfigTypeOptions, 'Master Access']
      : baseConfigTypeOptions;

  const TypeNames =
    AppType === 'Wholesale'
      ? ConfigTypeNames.filter((item) =>
        baseConfigTypeOptions.includes(item.TypeName)
      ) // include only these for Wholesale
      : ConfigTypeNames.filter(
        (item) => !baseConfigTypeOptions.includes(item.TypeName)
      );

  const [open, setOpen] = useState(false);
  const [EditState, setEditState] = useState(false);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [selectedRow, setSelectedRow] = useState(null);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [CommonDataFilter, setCommonDataFilter] = useState([]);
  const [showHomeComponent, setShowHomeComponent] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [radioValue, setRadioValue] = useState('single');
  const [categoryOpen, setCategoryOpen] = useState(false);
  const [categoryData, setCategoryData] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState();
  const [selectedSubCategory, setSelectedSubCategory] = useState();
  const [subCategoryOpen, setSubCategoryOpen] = useState(false);
  const [subCategoryData, setSubCategoryData] = useState([]);
  const [selectedNumericId, setselectedNumericId] = useState(null);
  const [page, setpage] = useState(1);

  const [Exceldatasubmit, setExceldatasubmit] = useState(null);
  const [openS, setOpenS] = useState(false);
  const [ProductCatdata, setProductCatdata] = useState();
  const [subCatData, setSubCatData] = useState();
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const excludeTypeNames = [
    'Product Category',
    'Product Sub-Category',
    'Product Brand',
    'Product Tax',
    'Designation',
    'Wholesale Extra Charges',
    'Wholesale Unit Of Measure',
    'Wholesale Quantity',
    'Wholesale Screen Name',
    'Wholesale Payment Mode',
    'Wholesale Designation',
  ];

  const systemTypes = [
    'Product Category',
    'Product Sub-Category',
    'Product Brand',
    'Product Tax',
    'Designation',
    'PackingType',
  ];
  useEffect(() => {
    try {
      dispatch(changeBreadCrumb({ items: items }));
      if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
        dispatch(getConfiguration({ Type: 'SA' })).unwrap();
        dispatch(getActiveConfigTypeNames({ Type: 'SA' })).unwrap();
      } else if (UserType === 'Admin' || UserType === 'Employee') {
        let TypeName = AppType === 'Wholesale' ? 'AW' : 'A';
        dispatch(getActiveConfigTypeNames({ Type: TypeName })).unwrap();
        dispatch(getConfiguration({ Type: TypeName })).unwrap();
      }
    } catch (err) {
      console.log(err, 'err');
    }
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
  }, []);
  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);
  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);

  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Common Master'
    );
    setEmpData(datas?.[0]);
  };

  useEffect(() => {
    if (AppType === 'Wholesale') {
      updateCommonDataFilter();
    } else {
      setCommonDataFilter([
        ...(Array.isArray(CommonData)
          ? CommonData.filter(
            (data) =>
              ![
                'Product Category',
                'Product Sub-Category',
                'Product Brand',
                'Product Tax',
                'Designation',
                'Wholesale Extra Charges',
                'Wholesale Unit Of Measure',
                'Wholesale Quantity',
                'Wholesale Screen Name',
                'Wholesale Payment Mode',
                'Wholesale Designation',
              ].includes(data?.TypeName)
          )
          : []),

        ...(Array.isArray(CommonData)
          ? CommonData.filter((data) =>
            [
              'Product Category',
              'Product Sub-Category',
              'Product Brand',
              'Product Tax',
              'Designation',
              'PackingType',
            ].includes(data?.TypeName)
          ).filter((item) => item.AlphaNumFId == AppId)
          : []),
      ]);
    }
  }, [CommonData]);

  const updateCommonDataFilter = () => {
    if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
      setCommonDataFilter(
        CommonData?.filter(
          (data) =>
            data?.TypeName === 'Master Access' ||
            ([
              'Designation',
              'Product Quality',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
              'Wholesale Designation',
            ].includes(data?.TypeName) &&
              data?.AlphaNumFId == AppId)
        )
      );
    } else {
      setCommonDataFilter(
        CommonData?.filter(
          (data) =>
            [
              'Designation',
              'Product Quality',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
              'Wholesale Designation',
            ].includes(data?.TypeName) && data?.AlphaNumFId == AppId
        )
      );
    }
  };

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };
  const handlePageChange = (current) => {
    setpage(current);
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const updateImageUrl = (url) => {
    setImageUrl(url);
  };
  //edit
  const actionsFormatter = async (row) => {
    if (row.ActiveStatus !== 'D') {
      await setOpen(true);
      await setEditState(true);
      setImageUrl(row.SmallIcon);
      form.setFieldsValue(row);
      setSelectedRow(row);
    }
  };

  const statusFormatter = async (row) => {
    let deleteData = {
      ConfigId: row.ConfigId,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
    };
    let response = await dispatch(deleteConfiguration(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
        dispatch(getConfiguration({ Type: 'SA' })).unwrap();
      } else if (UserType === 'Admin' || UserType === 'Employee') {
        let TypeName = AppType === 'Wholesale' ? 'AW' : 'A';
        dispatch(getConfiguration({ Type: TypeName })).unwrap();
      }
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    }
  };

  const openModal = () => {
    setOpen(true);
    setSelectedSubCategory(null);
    form.resetFields();
    // Reset the editState to false
    setEditState(false);
  };

  const handleDropDownChange = async (value) => {
    form.setFieldsValue({ TypeId: value });
    let SubCategoryData = TypeNames?.filter(
      (item) => item.TypeId == value && item.TypeName == 'Product Sub-Category'
    );
    if (SubCategoryData?.length > 0) {
      setCategoryOpen(true);
      setSubCategoryOpen(false);
      let CategoryData = await dispatch(
        getConfigTypeData({ TypeName: 'Product Category', AppId: AppId })
      ).unwrap();
      if (CategoryData?.data?.statusCode == 1) {
        setCategoryData(CategoryData?.data?.data);
        setSubCategoryData([]);
      }
    } else {
      setCategoryOpen(false);
      form.resetFields(['CategoryId']);
      setSelectedCategory();
    }

    let BrandData = TypeNames?.filter(
      (item) => item.TypeId == value && item.TypeName == 'Product Brand'
    );
    if (BrandData?.length > 0) {
      setSubCategoryOpen(true);
      setCategoryOpen(false);
      let SubCategoryData = await dispatch(
        getConfigTypeData({ TypeName: 'Product Sub-Category', AppId: AppId })
      ).unwrap();
      if (SubCategoryData?.data?.statusCode == 1) {
        setSubCategoryData(SubCategoryData?.data?.data);
        setCategoryData([]);
      }
    }
    if (SubCategoryData?.data?.data?.length == 0 && BrandData?.length == 0) {
      setCategoryOpen(false);
      setSubCategoryOpen(false);
      setSubCategoryData([]);
      setCategoryData([]);
      form.setFieldsValue({ NumFId: null });
    }
  };

  const handleCategoryDropDownChange = async (value) => {
    setSelectedCategory(value);
    form.setFieldsValue({ NumFId: value, CategoryId: value });
    setselectedNumericId(value);
  };

  const handleSubCategoryDropDownChange = async (value) => {
    setSelectedSubCategory(value);
    form.setFieldsValue({ NumFId: value, SubCategoryId: value });
    setselectedNumericId(value);
  };

  const ConfigSelect = async (e) => {
    e !== 'Select' && setpage(1);
    if (e === 'Select' && AppType != 'Wholesale') {
      setCommonDataFilter([
        ...CommonData?.filter(
          (data) =>
            ![
              'Product Category',
              'Product Sub-Category',
              'Product Brand',
              'Product Tax',
              'Designation',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
              'Wholesale Designation',
            ].includes(data?.TypeName)
        ),
        ...CommonData?.filter((data) =>
          [
            'Product Category',
            'Product Sub-Category',
            'Product Brand',
            'Product Tax',
            'Designation',
          ].includes(data?.TypeName)
        )?.filter((item) => item.AlphaNumFId == AppId),
      ]);
    } else if (AppType === 'Wholesale' && e === 'Select') {
      updateCommonDataFilter();
    } else if (AppType === 'Wholesale') {
      if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
        setCommonDataFilter(
          CommonData?.filter(
            (data) =>
              (data?.TypeName === 'Master Access' ||
                ([
                  'Designation',
                  'Product Quality',
                  'Wholesale Extra Charges',
                  'Wholesale Unit Of Measure',
                  'Wholesale Quantity',
                  'Wholesale Screen Name',
                  'Wholesale Payment Mode',
                  'Wholesale Designation',
                ].includes(data?.TypeName) &&
                  data?.AlphaNumFId == AppId)) &&
              data?.TypeId === parseInt(e)
          )
        );
      } else {
        setCommonDataFilter(
          CommonData?.filter(
            (data) =>
              [
                'Designation',
                'Product Quality',
                'Wholesale Extra Charges',
                'Wholesale Unit Of Measure',
                'Wholesale Quantity',
                'Wholesale Screen Name',
                'Wholesale Payment Mode',
                'Wholesale Designation',
              ].includes(data?.TypeName) &&
              data?.AlphaNumFId == AppId &&
              data?.TypeId === parseInt(e)
          )
        );
      }
    } else {
      const filteredItems = [
        ...CommonData?.filter(
          (data) =>
            ![
              'Product Category',
              'Product Sub-Category',
              'Product Brand',
              'Product Tax',
              'Designation',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
              'Wholesale Designation',
            ].includes(data?.TypeName)
        ),
        ...CommonData?.filter((data) =>
          [
            'Product Category',
            'Product Sub-Category',
            'Product Brand',
            'Product Tax',
            'Designation',
            'PackingType',
          ].includes(data?.TypeName)
        )?.filter((item) => item.AlphaNumFId == AppId),
      ]?.filter((item) => item?.TypeId === parseInt(e));
      setCommonDataFilter(filteredItems);
    }
  };

  const SearchFilterFun = async (value) => {
    const searchValue = value?.toLowerCase();

    if (AppType != 'Wholesale') {
      const relevantItems =
        CommonData?.filter((item) => {
          // ❌ Exclude unwanted types first
          if (excludeTypeNames.includes(item.TypeName)) return false;

          // ✅ For systemTypes, only include if AppId matches
          if (systemTypes.includes(item.TypeName)) {
            return item.AlphaNumFId == AppId;
          }

          // ✅ For all other types, include them
          return true;
        }) || [];

      // Optional: for reference, not used directly here

      // alert("jhi")

      const filteredItems = relevantItems.filter((item) => {
        const typeMatch = item?.TypeName?.toLowerCase().includes(searchValue);
        const configMatch =
          item?.ConfigName?.toLowerCase().includes(searchValue);
        return typeMatch || configMatch;
      });

      // console.log(relevantItems, "filteredItems");

      setCommonDataFilter(filteredItems);
    }

    // Filter by AppId first
    else if (AppType === 'Wholesale') {
      if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
        setCommonDataFilter(
          CommonData?.filter(
            (data) =>
              (data?.TypeName === 'Master Access' ||
                ([
                  'Designation',
                  'Product Quality',
                  'Wholesale Extra Charges',
                  'Wholesale Unit Of Measure',
                  'Wholesale Quantity',
                  'Wholesale Screen Name',
                  'Wholesale Payment Mode',
                ].includes(data?.TypeName) &&
                  data?.AlphaNumFId == AppId)) &&
              data?.TypeId === parseInt(e)
          )
        );
      } else {
        setCommonDataFilter(
          CommonData?.filter(
            (data) =>
              [
                'Payment Mode',
                'Designation',
                'Product Quality',
                'Wholesale Extra Charges',
                'Wholesale Unit Of Measure',
                'Wholesale Quantity',
                'Wholesale Screen Name',
                'Wholesale Payment Mode',
              ].includes(data?.TypeName) &&
              data?.AlphaNumFId == AppId &&
              data?.TypeId === parseInt(e)
          )
        );
      }
    }
  };

  const handleRadioChange = (value) => {
    setRadioValue(value);

    // Reset the form values
    form.resetFields();
  };

  const onSearch = (value) => {
    setSearchedText(value);
    SearchFilterFun(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
    SearchFilterFun(e?.target?.value);
  };
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Type Name',
      dataIndex: 'TypeName',
      key: 'TypeName',
      width: '100px',
      render: (text) => (
        <a style={{ color: 'black', width: '200px' }}>{text}</a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.TypeName)
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(record.ConfigName)
            ?.toLowerCase()
            .includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.TypeName?.localeCompare(b.TypeName),
      sortOrder: sortedInfo.columnKey === 'TypeName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Config Name',
      dataIndex: 'ConfigName',
      key: 'ConfigName',

      width: '100px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      sorter: (a, b) => a?.ConfigName?.localeCompare(b.ConfigName),
      sortOrder:
        sortedInfo.columnKey === 'ConfigName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '100px',
      align: 'center',
      render: (_, record, index) =>
        [
          ...CommonData?.filter(
            (data) =>
              ![
                'Product Category',
                'Product Sub-Category',
                'Product Brand',
                'Product Tax',
                'Designation',
                'Product Quality',
                'Wholesale Extra Charges',
                'Wholesale Unit Of Measure',
                'Wholesale Quantity',
                'Wholesale Screen Name',
                'Wholesale Payment Mode',
              ].includes(data?.TypeName)
          ),
          ...CommonData?.filter((data) =>
            [
              'Product Category',
              'Product Sub-Category',
              'Product Brand',
              'Product Tax',
              'Designation',
              'Product Quality',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
            ].includes(data?.TypeName)
          )?.filter((item) => item.AlphaNumFId == AppId),
        ]?.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                      (UserType === 'Super Admin User' &&
                        SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                      (UserType === 'Employee' &&
                        empData?.UpdateAccess === 'Y') ||
                      UserType === 'Admin'
                      ? actionsFormatter(record, index)
                      : ''
                  }
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                      (UserType === 'Super Admin User' &&
                        SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                      (UserType === 'Employee' &&
                        empData?.DeleteAccess === 'Y') ||
                      UserType === 'Admin'
                      ? statusFormatter(record)
                      : ''
                  }
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                      (UserType === 'Super Admin User' &&
                        SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                      (UserType === 'Employee' &&
                        empData?.DeleteAccess === 'Y') ||
                      UserType === 'Admin'
                      ? statusFormatter(record)
                      : ''
                  }
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];

  useEffect(() => {
    Bulkuploadsubdata();
  }, []);

  const Bulkuploadsubdata = async () => {
    let res = await dispatch(getProdCatData({ AppId: AppId })).unwrap();
    setProductCatdata(res?.data?.data);

    let response = await dispatch(
      getAllsubcatdata({ AppId: AppId, TypeName: 'Product Sub-Category' })
    ).unwrap();
    setSubCatData(response?.data?.data);
  };
  const handleCancel = () => {
    setImageUrl('');
    setOpen(false);
    handleResetExcelData();
  };
  const handleCancelNew = () => {
    setOpenS(false);
    setOpen(false);
    handleResetExcelData();
  };

  const openModal1 = () => {
    setOpenS(true);
  };

  const handleResetExcelData = () => {
    dispatch(emptyExcelData());
  };

  const handleSubmitbulk = (excelData) => {
    setExceldatasubmit(excelData);
  };
  const handleSubmit = async () => {
    if (radioValue === 'single') {
      const values = await form.validateFields();
      const AppCommonData = TypeNames?.filter((data) =>
        [
          'Product Category',
          'Product Sub-Category',
          'Product Brand',
          'Product Tax',
          'Designation',
          'Product Quality',
          'Wholesale Extra Charges',
          'Wholesale Unit Of Measure',
          'Wholesale Quantity',
          'Wholesale Screen Name',
          'Wholesale Payment Mode',
        ].includes(data?.TypeName)
      )?.filter((item) => item.TypeId == values.TypeId);
      const postData = {
        TypeId: values.TypeId,
        ConfigName: values.ConfigName,
        AlphaNumFId: AppCommonData?.length > 0 ? AppId : null,
        NumFId: selectedNumericId,
        SmallIcon: imageUrl,
        CreatedBy: getSession('UserId'),
      };

      let response = {};
      if (!EditState) {
        response = await dispatch(postConfiguration(postData)).unwrap();
      } else {
        if (selectedRow) {
          const AppCommonData = TypeNames?.filter((data) =>
            [
              'Product Category',
              'Product Sub-Category',
              'Product Brand',
              'Product Tax',
              'Designation',
              'Product Quality',
              'Wholesale Extra Charges',
              'Wholesale Unit Of Measure',
              'Wholesale Quantity',
              'Wholesale Screen Name',
              'Wholesale Payment Mode',
            ].includes(data?.TypeName)
          )?.filter((item) => item.TypeId == selectedRow.TypeId);
          const putData = {
            ConfigId: selectedRow.ConfigId,
            ConfigName: values.ConfigName,
            AlphaNumFId: AppCommonData?.length > 0 ? AppId : null,
            TypeId: selectedRow.TypeId,
            NumFId: selectedRow.NumFId,
            UpdatedBy: getSession('UserId'),
            SmallIcon: imageUrl,
            // AlphaNumFId: EditData.AlphaNumFId,
            // NumFId: EditData.NumFId,
          };
          response = await dispatch(putConfiguration(putData)).unwrap();
        }
      }

      if (response?.data?.statusCode == 1) {
        setImageUrl('');
        setMessageType('success');
        setMessageData(response?.data?.response);
        handleCancel();
        form.resetFields();
        setSelectedCategory();
        if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
          dispatch(getConfiguration({ Type: 'SA' })).unwrap();
        } else if (UserType === 'Admin' || UserType === 'Employee') {
          let TypeName = AppType === 'Wholesale' ? 'AW' : 'A';
          dispatch(getConfiguration({ Type: TypeName })).unwrap();
        }
      } else {
        setImageUrl('');
        setMessageType('error');
        setMessageData(response?.data?.response);
      }
    }
  };
  const handleSubmitNew = async () => {
    let FilterData = Exceldatasubmit?.filter((a) => a['CategoryName'] != '');

    if (FilterData && FilterData.length > 0) {
      const formattedData = FilterData.map((data) => {
        // Declare configDetails before any conditional logic
        let configDetails = [];

        // Validation logic based on TypeName
        if (data?.TypeName === 'Product Category') {
          configDetails.push({
            ConfigName: data?.CategoryName,
            // NumFId: data?.CategoryName, // Use CategoryName for NumFId
          });
        } else if (data?.TypeName === 'Product Sub-Category') {
          configDetails.push({
            ConfigName: data?.CategoryName,
            NumFId: data?.SubCategoryName, // Use SubCategory for NumFId
          });
        } else if (data?.TypeName === 'Product Brand') {
          configDetails.push({
            ConfigName: data?.SubCategoryName,
            NumFId: data?.BrandName, // Use Brand for NumFId
          });
        } else {
          // Handle unrecognized TypeName
          console.error(`Unknown TypeName: ${data?.TypeName}`);
        }

        // Return the formatted object
        return {
          TypeName: data?.TypeName,
          AlphaNumFId: getSession('AppId'),
          CreatedBy: getSession('UserId'),
          ConfigDetails: configDetails,
        };
      });

      let postData = { configMasterDetailsJson: formattedData };

      let response = await dispatch(postbulkconfigdata(postData)).unwrap();
      if (response?.data?.statusCode == 1) {
        setMessageType('success');
        setMessageData(response?.data?.response);
        dispatch(getConfiguration({ Type: 'SA' }));
      } else {
        setMessageType('error');
        setMessageData(response?.data?.response);
      }

      handleResetExcelData();
      handleCancelNew();
    } else {
      setMessageType('error');
      setMessageData('No data to submit. Please upload an Excel file.');
    }
  };

  const CategoryNames = ProductCatdata?.map((e) => e.ConfigName);
  const Subcatnames = subCatData?.map((e) => e.ConfigName);

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="CommmasterPageHeader">
          <div>
            <FormHeader title={'Common Master'} />
          </div>
          <div className="formFields">
            <div className="formSearch">
              <Search
                placeholder="Search by Type Name/Config Name"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
            {/* {CommonDataFilter?.length > 0 &&  */}
            <Form.Item
              name="Config Type"
              rules={[
                {
                  required: true,
                  message: 'Please Select Config Type',
                },
              ]}
            >
              <DropDowns
                options={[
                  { value: 'Select', label: 'All' }, // Add "Select" option
                  ...TypeNames?.map((option) => ({
                    value: option.TypeId,
                    label: option.TypeName,
                  })),
                ]}
                defaultValue="Select" // Set "Select" as the default value
                // placeholder="Config Type"
                label="Config Type"
                onChangeFunction={(e) => ConfigSelect(e)}
                isOnchanges={true}
                className="field-DropDown"
                onFilter={(value, record) =>
                  String(record.TypeName)
                    ?.toLowerCase()
                    ?.includes(value?.toLowerCase())
                }
              />
            </Form.Item>
            {/* // } */}
          </div>
        </div>
        <div>
          {AppType !== 'Wholesale' ? (
            <div
              className="commonMaster-btn"
              style={{
                display: 'flex',
                height: '50px',
                gap: '5px',
                justifyContent: 'flex-end',
              }}
            >
              <div>
                <TertiaryButton
                  buttonText="Import / Export Excel"
                  className="tertiary_Button"
                  disabled={addnewAccess}
                  handleSubmit={openModal1}
                />
              </div>
              <div>
                <div className="productMaster-input">
                  <Buttons
                    buttonText="Add New"
                    className="tertiary_Button"
                    color="901D77"
                    handleSubmit={openModal}
                    disabled={addnewAccess}
                    icon={<PlusOutlined />}
                  >
                    OPEN
                  </Buttons>
                </div>
              </div>
            </div>
          ) : (
            <div>
              <div className="productMaster-input">
                <Buttons
                  buttonText="Add New"
                  className="tertiary_Button"
                  color="901D77"
                  handleSubmit={openModal}
                  disabled={addnewAccess}
                  icon={<PlusOutlined />}
                >
                  OPEN
                </Buttons>
              </div>
            </div>
          )}
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={CommonDataFilter}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>

      <DefaultModal
        open={open}
        title="Common Master"
        footer={true}
        children={
          <>
            <div className="configMsrMainDiv">
              <Form form={form}>
                <div className="configMsrSubDiv">
                  <Form.Item
                    name="TypeId"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Config Type',
                      },
                    ]}
                  >
                    <DropDowns
                      options={[
                        // { value: "Select", label: "All" }, // Add "Select" option
                        ...TypeNames?.map((option) => ({
                          value: option.TypeId,
                          label: option.TypeName,
                        })),
                      ]}
                      // placeholder="ConfigType"
                      label={<label class="required">Config Type</label>}
                      optionsNames={{ value: 'TypeId', label: 'TypeName' }}
                      className="field-DropDown"
                      // isOnchanges={true}
                      onChangeFunction={handleDropDownChange}
                      // defaultValue="Select" // Set "Select" as the default value
                      valueData={EditState ? selectedRow?.TypeId : undefined}
                      disabled={!!EditState}
                    />
                  </Form.Item>
                  {categoryOpen && (
                    <Form.Item
                      name="CategoryId"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select Category',
                        },
                      ]}
                    >
                      <DropDowns
                        options={[
                          //  // Add "Select" option
                          //  { value: "Select", label: "All" },
                          ...categoryData?.map((option) => ({
                            value: option.ConfigId,
                            label: option.ConfigName,
                          })),
                        ]}
                        // placeholder="Category"
                        label={<label class="required">Category</label>}
                        optionsNames={{
                          value: 'ConfigId',
                          label: 'ConfigName',
                        }}
                        className="field-DropDown"
                        // isOnchanges={true}
                        onChangeFunction={handleCategoryDropDownChange}
                        // defaultValue="Select" // Set "Select" as the default value
                        valueData={selectedCategory}
                      />
                    </Form.Item>
                  )}
                  {subCategoryOpen && (
                    <Form.Item
                      name="SubCategoryId"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select SubCategory',
                        },
                      ]}
                    >
                      <DropDowns
                        options={[
                          //  // Add "Select" option
                          //  { value: "Select", label: "All" },
                          ...subCategoryData?.map((option) => ({
                            value: option.ConfigId,
                            label: option.ConfigName,
                          })),
                        ]}
                        // placeholder="Sub-Category"
                        label={<label class="required">Sub-Category</label>}
                        optionsNames={{
                          value: 'ConfigId',
                          label: 'ConfigName',
                        }}
                        className="field-DropDown"
                        // isOnchanges={true}
                        onChangeFunction={handleSubCategoryDropDownChange}
                        // defaultValue="Select" // Set "Select" as the default value
                        valueData={selectedSubCategory}
                      />
                    </Form.Item>
                  )}
                  <Form.Item
                    name="ConfigName"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter Config Name',
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value);

                          if (value && value.length > 50) {
                            return Promise.reject(
                              'Config Name should not exceed 50 characters'
                            );
                          }

                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      label={<label class="required">Config Name</label>}
                      autocomplete="off"
                      isOnChange={EditState ? true : false}
                    />
                  </Form.Item>
                </div>

                <div className="upload_btn">
                  <p>Upload Icon</p>
                  <br />
                  <div style={{ width: 'max-content' }}>
                    <Imageupload
                      singleImage={true}
                      updateImageUrl={updateImageUrl}
                      ImageLink={imageUrl ? imageUrl : ''}
                    />
                  </div>
                </div>
              </Form>
            </div>
            {radioValue === 'multiple' && !EditState && (
              // Render the content for the "Multiple" option
              <div>
                <ConfigExcel
                  handleSubmit={handleSubmitbulk}
                  showHomeComponent={showHomeComponent}
                />
              </div>
            )}
          </>
        }
        handleCancel={handleCancel}
        handleSubmit={handleSubmit}
      />
      <DefaultModal
        open={openS}
        title="Bulk Upload"
        footer={true}
        width={700}
        children={
          <>
            <ConfigExcel
              CategoryNames={CategoryNames}
              SubCatData={Subcatnames}
              handleSubmit={handleSubmitbulk}
            />
          </>
        }
        handleSubmit={handleSubmitNew}
        handleCancel={handleCancelNew}
      />
    </div>
  );
};

export default CommonMaster;
