/**
 * User Preferences Hook
 *
 * @package
 * @since   0.1.0
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { useNotification } from '../contexts/NotificationContext';

/**
 * Hook for managing user preferences
 *
 * @return {Object} User preferences state and methods
 */
export const useUserPreferences = () => {
  const [preferences, setPreferences] = useState({
    expert_mode: false,
    pinned_modules: [],
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { showNotification } = useNotification();

  /**
   * Fetch user preferences from the API
   *
   * @return {Promise<void>}
   */
  const fetchPreferences = useCallback(async () => {
    try {
      // TODO: Fix REST API endpoint
      /*
      const response = await apiFetch({
        path: '/prorank-seo/v1/user/preferences',
        method: 'GET',
      });

      if (response.success === true && response.data !== null && response.data !== undefined) {
        setPreferences(response.data);
      }
      */

      // Use default preferences for now
      setPreferences({
        expert_mode: false,
        pinned_modules: [],
      });
    } catch (error) {
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch preferences on mount
  useEffect(() => {
    fetchPreferences();
  }, [fetchPreferences]);

  /**
   * Update user preferences
   *
   * @param {Object} updates - Preference updates to apply
   * @return {Promise<void>}
   */
  const updatePreferences = useCallback(
    async (updates) => {
      setSaving(true);

      try {
        // TODO: Fix REST API endpoint
        /*
        const response = await apiFetch({
          path: '/prorank-seo/v1/user/preferences',
          method: 'POST',
          data: {
            preferences: updates,
          },
        });

        if (response.success === true && response.data !== null && response.data !== undefined) {
          setPreferences((prev) => ({
            ...prev,
            ...response.data.updated,
          }));
        }
        */

        // Update locally for now
        setPreferences((prev) => ({
          ...prev,
          ...updates,
        }));

        showNotification(__('Preferences updated.', 'prorank-seo'), 'success');
      } catch (error) {
        showNotification(
          __('Failed to update preferences. Please try again.', 'prorank-seo'),
          'error'
        );
      } finally {
        setSaving(false);
      }
    },
    [showNotification]
  );

  /**
   * Toggle expert mode on/off
   *
   * @return {Promise<void>}
   */
  const toggleExpertMode = useCallback(async () => {
    setSaving(true);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/user/expert-mode',
        method: 'POST',
        data: {
          enabled: !preferences.expert_mode,
        },
      });

      if (response.success === true && response.data !== null && response.data !== undefined) {
        setPreferences((prev) => ({
          ...prev,
          expert_mode: response.data.enabled,
        }));

        showNotification(response.data.message, 'success');
      }
    } catch (error) {
      showNotification(
        __('Failed to toggle expert mode. Please try again.', 'prorank-seo'),
        'error'
      );
    } finally {
      setSaving(false);
    }
  }, [preferences.expert_mode, showNotification]);

  /**
   * Toggle a module's pinned status
   *
   * @param {string} moduleSlug - The module slug to toggle
   * @return {Promise<boolean>} Whether the module is now pinned
   */
  const togglePinnedModule = useCallback(
    async (moduleSlug) => {
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/user/pinned-modules/toggle',
          method: 'POST',
          data: {
            module: moduleSlug,
          },
        });

        if (response.success === true && response.data !== null && response.data !== undefined) {
          setPreferences((prev) => ({
            ...prev,
            pinned_modules: response.data.modules,
          }));

          showNotification(response.data.message, 'success');

          return response.data.is_pinned;
        }
      } catch (error) {
        showNotification(
          __('Failed to update pinned modules. Please try again.', 'prorank-seo'),
          'error'
        );
      }

      return false;
    },
    [showNotification]
  );

  /**
   * Check if a module is pinned
   *
   * @param {string} moduleSlug - The module slug to check
   * @return {boolean} Whether the module is pinned
   */
  const isModulePinned = useCallback(
    (moduleSlug) => {
      return preferences.pinned_modules.includes(moduleSlug);
    },
    [preferences.pinned_modules]
  );

  return {
    preferences,
    loading,
    saving,
    isExpertMode: preferences.expert_mode,
    pinnedModules: preferences.pinned_modules,
    updatePreferences,
    toggleExpertMode,
    togglePinnedModule,
    isModulePinned,
    refetch: fetchPreferences,
  };
};
