import  apiService from '../../src/APIRequestService/APIService';
    
export const fetchMenuItems = async () => {
  console.log("applying fetch menu items");
  try {
    const response = await apiService.get('/api1/submenu1');
    console.log("response", response);

    // Check for a successful response
    if (response.status !== 200) {
      throw new Error(`Error: ${response.status}`);
    }

    // Ensure that the response has a proper 'data' field and is an array
    if (!response.data || !Array.isArray(response.data)) {
      throw new Error('Unexpected data format, expected an array');
    }

    console.log('Fetched Menu Items:', response.data);
    return response.data;  // Return the correct data
  } catch (error) {
    console.error('Error fetching menu items:', error);
    throw error;  // Re-throw the error to be caught by the calling function
  }
};

// export const addMenuItem = async (formData) => {
//   try {
//     const response = await apiService.post('/api1/Sec_menuDet', formData);
//     console.log("add response: ",response.data);
//     return response.data; // Return only the data part of the response
//   } catch (error) {
//     throw error; // Let the error be handled by the calling component
    
//   }   
// }

export const addMenuItem = async (formData) => {
  try {
    const payload = {
      menuItemDesc: formData.menuItemDesc,
      menuId: 0,
      itemSeq: formData.itemSeq || 0,
      moduleName: formData.moduleName || "",
      main_menu_action_name: formData.main_menu_action_name || "#",
      main_menu_icon_name: formData.main_menu_icon_name || "fa-circle",
      status: formData.status === "true"
    };
    
    console.log("Final payload:", payload);
    
    // Remove the duplicate '/back' from the endpoint
    const response = await apiService.post('/api1/Sec_menuDet/', payload);
    return response.data;
  } catch (error) {
    console.error('Error adding menu item:', error);
    throw error;
  }
};


export const updateMenuItem = async (id, formData) => {
  try {
    // Payload with ALL required fields (never change menuItemId)
    const payload = {
      menuItemId: Number(id),  // Keep original ID
      menuItemDesc: formData.menuItemDesc,
      menuId: formData.menuId || 0, // Keep original parent ID
      itemSeq: formData.itemSeq || 0,
      moduleName: formData.moduleName || "",
      main_menu_action_name: formData.main_menu_action_name || "#",
      main_menu_icon_name: formData.main_menu_icon_name || "fa-circle",
      status: formData.status === "Enable" || formData.status === true
    };

    console.log("Updating menu item #"+id, payload);
    
    // POST request with full payload (confirmed working)
    const response = await apiService.post('/api1/Sec_menuDet/', payload);
    
    console.log("Update successful:", response.data);
    return response.data;
    
  } catch (error) {
    console.error('Update failed:', {
      id: id,
      error: error.response?.data || error.message
    });
    throw error;
  }
};


export const deleteMenuItem = async (id) => {
  try {
    const response = await apiService.delete(`/api1/menu/${id}`);
    return response.data; // Return only the data part of the response
  } catch (error) {
    throw error; // Let the error be handled by the calling component
  }
}
// submenu apis

export const getSubmenuItems = async (id) => {
  try {
    
    const response = await apiService.get(`/api1/submenu1/${id}`);
    console.log("get submenu response: ", response.data);
    return response.data; // Return only the data part of the response
  } catch (error) {
    throw error; // Let the error be handled by the calling component
  }
}

// export const addSubmenuItem = async (menuId, formData) => {
//   try {
//     const response = await apiService.post(`/api1/submenu1/${menuId}`, formData);
//     console.log("add subMenu response: ",response.data);
//     return response.data; // Return only the data part of the response
//   } catch (error) {
//     throw error; // Let the error be handled by the calling component
// }
// }


// export const addSubmenuItem = async (menuId, formData) => {
//   try {
//     console.log("adding submenu item");
//     console.log("menuid", menuId);

//     const response = await apiService.post(`/api1/submenu1/${menuId}`, formData);
//     console.log("menuid", menuId);
//     console.log("add subMenu response: ", response.data);
//     return response.data; // Return only the data part of the response
//   } catch (error) {
//     throw error; // Let the error be handled by the calling component
//   }
// }


// Update the MenuMaintenanceAPI.js to handle single object
// export const addSubmenuItem = async (menuId, formData) => {
//   try {
//     // Convert string numbers to proper numbers
//     const payload = {
//       ...formData,
//       menuItemId: Number(formData.menuItemId), // Convert to number
//       itemSeq: Number(formData.itemSeq),       // Convert to number
//       menuId: Number(menuId)                  // Ensure parent ID is number
//     };

//     console.log("Final payload with converted numbers:", payload);

//     const response = await apiService.put(`/api1/submenu1`, payload, { // Changed to POST
//       headers: {
//         'Content-Type': 'application/json'
//       }
//     });

//     // Verify the response contains all required fields
//     if (!response.data?.menuItemId) {
//       throw new Error("Incomplete response from server");
//     }

//     return response.data;
//   } catch (error) {
//     console.error("API Error Details:", {
//       request: error.config?.data,
//       response: error.response?.data
//     });
//     throw error;
//   }
// };
  
export const addSubmenuItem = async (parentMenuId, formData) => {
  try {
    // Prepare payload - same structure as main menu but with parent ID relationship
    const payload = {
      menuItemDesc: formData.menuItemDesc,
      menuId: Number(parentMenuId), // This establishes the parent-child relationship
      itemSeq: formData.itemSeq || 0,
      moduleName: formData.moduleName || "",
      main_menu_action_name: formData.main_menu_action_name || "#",
      main_menu_icon_name: formData.main_menu_icon_name || "fa-circle",
      status: formData.status === "Enable" // Convert to boolean
    };

    console.log("Adding submenu with payload:", payload);
    
    // Use the same endpoint as main menu
    const response = await apiService.post('/api1/Sec_menuDet/', payload);
    
    return response.data;
  } catch (error) {
    console.error('Error adding submenu:', error);
    throw error;
  }
};

export const updateSubmenuItem = async (submenuId, formData) => {
   const payload = {
      menuItemId: Number(submenuId), // ID in the body
      menuItemDesc: formData.menuItemDesc,
      menuId: Number(formData.menuId), // Parent menu ID
      itemSeq: formData.itemSeq || 0,
      moduleName: formData.moduleName || "",
      main_menu_action_name: formData.main_menu_action_name || "#",
      main_menu_icon_name: formData.main_menu_icon_name || "fa-circle",
      status: formData.status === "Enable" || formData.status === true
    };
  try {
    const payload = {
      menuItemId: Number(submenuId), // ID in the body
      menuItemDesc: formData.menuItemDesc,
      menuId: Number(formData.menuId), // Parent menu ID
      itemSeq: formData.itemSeq || 0,
      moduleName: formData.moduleName || "",
      main_menu_action_name: formData.main_menu_action_name || "#",
      main_menu_icon_name: formData.main_menu_icon_name || "fa-circle",
      status: formData.status === "Enable" || formData.status === true
    };

    console.log("Updating submenu with payload:", payload);
    
    // Using POST with ID in body (confirmed working)
    const response = await apiService.post('/api1/Sec_menuDet/', payload);
    return response.data;
    
  } catch (error) {
    console.error('Error updating submenu:', {
      error: error.response?.data || error.message,
      payload: payload
    });
    throw error;
  }
};
export const deleteSubmenuItem = async (submenuId) => {
  try {
    console.log("Deleting submenu with ID:", submenuId);
    
    // Using the working POST method with just menuItemId
    const response = await apiService.post('/api1/Sec_menuDet/', {
      menuItemId: Number(submenuId)  // Only sending the ID as confirmed to work
    });
    
    console.log("Delete successful:", response.data);
    return response.data;
    
  } catch (error) {
    console.error('Error deleting submenu:', {
      status: error.response?.status,
      error: error.response?.data || error.message,
      submenuId: submenuId
    });
    throw error;
  }
};