// src/hooks/use-member-tiers.js
import { useState, useEffect, useCallback } from 'react';
import api from '../utils/api';
import { DEFAULT_MEMBER_TIERS } from '../config/MemberTiers';

/**
 * Hook for fetching and managing member tier configuration
 * @param {Object} options
 * @param {boolean} options.isAdmin - Whether to use admin endpoint (includes metadata)
 * @returns {Object} Tier state and methods
 */
const useMemberTiers = ({ isAdmin = false } = {}) => {
  const [tiers, setTiers] = useState(DEFAULT_MEMBER_TIERS);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [saving, setSaving] = useState(false);

  const endpoint = isAdmin
    ? '/admin/settings/member-tiers'
    : '/settings/member-tiers';

  const fetchTiers = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await api.get(endpoint);
      const data = response.data?.tiers || response.data || DEFAULT_MEMBER_TIERS;
      setTiers(data);
    } catch (err) {
      console.error('Failed to fetch member tiers:', err);
      setError('Failed to load member tiers');
      // Use defaults on error
      setTiers(DEFAULT_MEMBER_TIERS);
    } finally {
      setLoading(false);
    }
  }, [endpoint]);

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

  /**
   * Update tier configuration (admin only)
   * @param {Array} newTiers - Updated tier array
   * @returns {Promise<boolean>} Success status
   */
  const updateTiers = useCallback(async (newTiers) => {
    if (!isAdmin) {
      console.error('updateTiers requires admin access');
      return false;
    }

    try {
      setSaving(true);
      setError(null);
      await api.put('/admin/settings/member-tiers', { tiers: newTiers });
      setTiers(newTiers);
      return true;
    } catch (err) {
      console.error('Failed to update member tiers:', err);
      setError('Failed to save member tiers');
      return false;
    } finally {
      setSaving(false);
    }
  }, [isAdmin]);

  /**
   * Reset tiers to defaults (superadmin only)
   * @returns {Promise<boolean>} Success status
   */
  const resetToDefaults = useCallback(async () => {
    if (!isAdmin) {
      console.error('resetToDefaults requires admin access');
      return false;
    }

    try {
      setSaving(true);
      setError(null);
      const response = await api.post('/admin/settings/member-tiers/reset');
      const data = response.data?.tiers || response.data || DEFAULT_MEMBER_TIERS;
      setTiers(data);
      return true;
    } catch (err) {
      console.error('Failed to reset member tiers:', err);
      setError('Failed to reset member tiers');
      return false;
    } finally {
      setSaving(false);
    }
  }, [isAdmin]);

  return {
    tiers,
    loading,
    error,
    saving,
    fetchTiers,
    updateTiers,
    resetToDefaults,
  };
};

export default useMemberTiers;
