import { useState, useEffect } from 'react';
import { getNoticeData } from '../Helpers';

/**
 * Custom hook for managing component settings with localStorage and API sync
 * @param {string} settingsKey - The settings key for localStorage
 * @param {object} defaultSettings - Default settings object
 * @param {string} apiEndpoint - API endpoint for saving settings
 * @returns {object} - Settings management utilities
 */
export const useComponentSettings = (settingsKey, defaultSettings, apiEndpoint) => {
  const [credentials, setCredentials] = useState({});
  const [settings, setSettings] = useState(defaultSettings);
  const [passview, setPassview] = useState(false);
  const [getGlobalURL, setGetGlobalURL] = useState(false);

  // Generate site-specific localStorage key
  const getSiteIdentifier = () => {
    const pathParts = window.location.pathname.split("/").filter(Boolean);
    const indexOfAdmin = pathParts.indexOf('wp-admin');
    return indexOfAdmin !== -1 
      ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() 
      : pathParts.slice(-1).pop();
  };

  const localStorageKey = `wpnts_${settingsKey}_settings_${getSiteIdentifier()}`;

  // Initialize settings from API data or localStorage
  useEffect(() => {
    getWebhook();
  }, []);

  function getWebhook() {
    // Get data from API based on the original structure
    let apiData;
    if (settingsKey === 'comment') {
      apiData = getNoticeData().wpnts_schedules_interval_comment_settings || defaultSettings;
    } else if (settingsKey === 'author') {
      apiData = getNoticeData().wpnts_default_interval || defaultSettings;
    } else if (settingsKey === 'captcha') {
      apiData = getNoticeData().wpnts_schedules_interval_debuglog_settings || defaultSettings;
    } else if (settingsKey === 'woocommerce') {
      apiData = getNoticeData().wpnts_schedules_interval_woocommerce_settings || defaultSettings;
    } else if (settingsKey === 'media') {
      apiData = getNoticeData().wpntswebhook_media_settings || defaultSettings;
    } else if (settingsKey === 'security') {
      apiData = getNoticeData().wpnts_webhook_site_settings || defaultSettings;
    } else if (settingsKey === 'debugger') {
      apiData = getNoticeData().wpnts_schedules_interval_debuglog_settings || defaultSettings;
    } else if (settingsKey === 'downtimealerts') {
      apiData = getNoticeData().wpnts_schedules_interval_website_downtime_alerts || defaultSettings;
    } else if (settingsKey === 'emergency') {
      apiData = getNoticeData().wpntswebhook_emengency_shutdown || defaultSettings;
    } else if (settingsKey === 'maintenance') {
      apiData = getNoticeData().wpnts_schedules_maintenannotice_settings || defaultSettings;
    } else if (settingsKey === 'menu') {
      apiData = getNoticeData().wpntswebhook_menu_settings || defaultSettings;
    } else if (settingsKey === 'pagenpost') {
      apiData = getNoticeData().wpntswebhook_pagenpost_settings || defaultSettings;
    } else if (settingsKey === 'site') {
      apiData = getNoticeData().wpnts_schedules_interval_site_settings || defaultSettings;
    } else if (settingsKey === 'theme') {
      apiData = getNoticeData().wpntswebhook_theme_settings || defaultSettings;
    } else if (settingsKey === 'wpwidgets') {
      apiData = getNoticeData().wpntswebhook_widget_settings || defaultSettings;
    } else {
      apiData = defaultSettings;
    }

    // Merge default settings with API data to ensure all fields are present
    const mergedApiData = { ...defaultSettings, ...apiData };
    const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(mergedApiData));
    
    // Ensure the final data has all default fields
    const finalData = { ...defaultSettings, ...formData };
    setCredentials(finalData);
  }

  // Update settings when credentials change
  useEffect(() => {
    setSettings(credentials);
  }, [credentials]);

  // Generic handlers
  const handleChange = (e) => {
    setSettings(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleToggle = (fieldName) => (value) => {
    setSettings(prev => ({ ...prev, [fieldName]: value }));
  };

  const handleCheckbox = (fieldName) => (e) => {
    const isChecked = e.target.checked;
    setSettings(prev => ({ ...prev, [fieldName]: isChecked }));
  };

  const handleSelectChange = (fieldName) => (e) => {
    const selectedValue = parseInt(e.target.value, 10);
    setSettings(prev => ({ ...prev, [fieldName]: selectedValue }));
  };

  const handleViewpass = () => {
    setPassview(prev => !prev);
  };

  const handleGetGlobalURLChange = (globalWebhook) => {
    setSettings(prev => ({ ...prev, webhook: globalWebhook }));
    setGetGlobalURL(true);
  };

  // Save settings to localStorage
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem(localStorageKey, JSON.stringify(settings));
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  };

  return {
    settings,
    setSettings,
    passview,
    getGlobalURL,
    setGetGlobalURL,
    handleChange,
    handleToggle,
    handleCheckbox,
    handleSelectChange,
    handleViewpass,
    handleGetGlobalURLChange,
    saveToLocalStorage,
    localStorageKey
  };
};