/**
 * useFeatureAccess Hook
 *
 * Provides tier-based feature access control for Mawidi dashboard
 * Determines which features are available based on user's subscription tier
 */

import { useMemo } from "react";

// Tier level mapping (tier1 = Starter, tier2 = Professional, etc.)
const TIER_LEVELS: Record<string, number> = {
  tier1: 1,
  tier2: 2,
  tier3: 3,
  tier4: 4,
  tier5: 5,
};

// Feature requirements (minimum tier level needed)
const FEATURE_REQUIREMENTS = {
  // Tier 1 - Starter (All users)
  aiAgent: 1,
  whatsapp: 1,
  appointments: 1,
  reviews: 1,

  // Tier 2 - Professional
  quotations: 2,
  crm: 2,
  integrations: 2,
  deposits: 2,

  // Tier 3 - Business
  aiWorkflows: 3,
  voiceReceptionist: 3,
  multiStaffLogin: 3,
  recurringAppointments: 3,

  // Tier 4 - Enterprise
  socialManagement: 4,
  aiSocialAssistant: 4,

  // Tier 5 - Ultimate
  leadGeneration: 5,
  leadScoring: 5,
  whiteLabel: 5,
} as const;

export type FeatureName = keyof typeof FEATURE_REQUIREMENTS;

interface UseFeatureAccessReturn {
  /**
   * Check if user has access to a specific feature
   * @param feature - Feature name to check
   * @returns true if user has access, false otherwise
   */
  hasFeature: (feature: FeatureName) => boolean;

  /**
   * Get the required tier name for a feature
   * @param feature - Feature name to check
   * @returns Human-readable tier name (e.g., "Professional")
   */
  getRequiredTier: (feature: FeatureName) => string;

  /**
   * Current user's tier level (1-5)
   */
  currentTier: number;

  /**
   * All available features for current tier
   */
  availableFeatures: FeatureName[];

  /**
   * All locked features for current tier
   */
  lockedFeatures: FeatureName[];
}

/**
 * Hook to check feature access based on package tier
 * @param packageTier - User's current package tier (tier1, tier2, etc.)
 * @returns Feature access utilities
 */
export function useFeatureAccess(packageTier: string): UseFeatureAccessReturn {
  // Get user's tier level (default to tier1 if invalid)
  const userTierLevel = TIER_LEVELS[packageTier] || 1;

  // Memoize hasFeature function to avoid recreating on every render
  const hasFeature = useMemo(() => {
    return (feature: FeatureName): boolean => {
      const requiredLevel = FEATURE_REQUIREMENTS[feature];
      if (typeof requiredLevel !== "number") {
        console.warn(`Unknown feature: ${feature}`);
        return false;
      }
      return userTierLevel >= requiredLevel;
    };
  }, [userTierLevel]);

  // Get required tier name for a feature
  const getRequiredTier = (feature: FeatureName): string => {
    const level = FEATURE_REQUIREMENTS[feature] || 1;
    const tierNames = [
      "Starter",
      "Professional",
      "Business",
      "Enterprise",
      "Ultimate",
    ];
    return tierNames[level - 1] || "Starter";
  };

  // Calculate available and locked features
  const { availableFeatures, lockedFeatures } = useMemo(() => {
    const available: FeatureName[] = [];
    const locked: FeatureName[] = [];

    (Object.keys(FEATURE_REQUIREMENTS) as FeatureName[]).forEach((feature) => {
      if (hasFeature(feature)) {
        available.push(feature);
      } else {
        locked.push(feature);
      }
    });

    return { availableFeatures: available, lockedFeatures: locked };
  }, [hasFeature]);

  return {
    hasFeature,
    getRequiredTier,
    currentTier: userTierLevel,
    availableFeatures,
    lockedFeatures,
  };
}

/**
 * Get tier display name from tier ID
 */
export function getTierDisplayName(tierId: string): string {
  const level = TIER_LEVELS[tierId] || 1;
  const tierNames = [
    "Starter",
    "Professional",
    "Business",
    "Enterprise",
    "Ultimate",
  ];
  return tierNames[level - 1] || "Starter";
}

/**
 * Get all tier levels with their display names
 */
export function getAllTiers() {
  return [
    { id: "tier1", level: 1, name: "Starter" },
    { id: "tier2", level: 2, name: "Professional" },
    { id: "tier3", level: 3, name: "Business" },
    { id: "tier4", level: 4, name: "Enterprise" },
    { id: "tier5", level: 5, name: "Ultimate" },
  ];
}
