/**
 * useFeatureFlags Hook
 * React Query hooks for Feature Flags
 * @created Sprint 2 - TASK-2026-01-30-ANALISIS-INTEGRACION
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../lib/apiClient';

// ============================================================================
// Types
// ============================================================================

export type FlagStatus = 'disabled' | 'enabled' | 'percentage';
export type RolloutStage = 'development' | 'beta' | 'production';

export interface FeatureFlag {
  id: string;
  code: string;
  name: string;
  description: string | null;
  category: string;
  status: FlagStatus;
  rolloutStage: RolloutStage;
  rolloutPercentage: number;
  defaultValue: boolean;
  targetingRules: TargetingRule[];
  metadata: Record<string, unknown>;
  tags: string[];
  isPermanent: boolean;
  expiresAt: Date | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface TargetingRule {
  type: 'plan' | 'role' | 'user_attribute';
  operator: 'eq' | 'neq' | 'in' | 'not_in' | 'gt' | 'lt';
  attribute?: string;
  value?: string;
  values?: string[];
}

export interface FlagEvaluation {
  flagCode: string;
  enabled: boolean;
  reason: string;
}

export interface CreateFlagInput {
  code: string;
  name: string;
  description?: string;
  category?: string;
  status?: FlagStatus;
  rolloutPercentage?: number;
  defaultValue?: boolean;
}

// ============================================================================
// API Functions
// ============================================================================

async function getAllFlags(): Promise<FeatureFlag[]> {
  const response = await apiClient.get('/feature-flags');
  return response.data.data;
}

async function evaluateAllFlags(): Promise<FlagEvaluation[]> {
  const response = await apiClient.get('/feature-flags/evaluate');
  return response.data.data;
}

async function evaluateFlag(code: string): Promise<{ code: string; enabled: boolean }> {
  const response = await apiClient.get(`/feature-flags/evaluate/${code}`);
  return response.data.data;
}

async function checkFlag(code: string): Promise<boolean> {
  const response = await apiClient.get(`/feature-flags/check/${code}`);
  return response.data.enabled;
}

async function createFlag(input: CreateFlagInput): Promise<FeatureFlag> {
  const response = await apiClient.post('/feature-flags', input);
  return response.data.data;
}

async function toggleFlag(id: string, enabled: boolean): Promise<FeatureFlag> {
  const response = await apiClient.post(`/feature-flags/${id}/toggle?enabled=${enabled}`);
  return response.data.data;
}

// ============================================================================
// React Query Hooks
// ============================================================================

/**
 * Get all feature flags (admin)
 */
export function useFeatureFlags() {
  return useQuery({
    queryKey: ['feature-flags', 'all'],
    queryFn: getAllFlags,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Evaluate all flags for current user
 */
export function useFlagEvaluations() {
  return useQuery({
    queryKey: ['feature-flags', 'evaluations'],
    queryFn: evaluateAllFlags,
    staleTime: 60 * 1000, // 1 minute
  });
}

/**
 * Evaluate a single flag
 */
export function useFlagEvaluation(code: string) {
  return useQuery({
    queryKey: ['feature-flags', 'evaluate', code],
    queryFn: () => evaluateFlag(code),
    staleTime: 60 * 1000,
    enabled: !!code,
  });
}

/**
 * Quick check if flag is enabled
 */
export function useFlagCheck(code: string) {
  return useQuery({
    queryKey: ['feature-flags', 'check', code],
    queryFn: () => checkFlag(code),
    staleTime: 60 * 1000,
    enabled: !!code,
  });
}

/**
 * Create a new flag
 */
export function useCreateFlag() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createFlag,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['feature-flags'] });
    },
  });
}

/**
 * Toggle flag status
 */
export function useToggleFlag() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) => toggleFlag(id, enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['feature-flags'] });
    },
  });
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Get status badge color
 */
export function getFlagStatusColor(status: FlagStatus): string {
  const colors: Record<FlagStatus, string> = {
    disabled: 'bg-gray-100 text-gray-800',
    enabled: 'bg-green-100 text-green-800',
    percentage: 'bg-blue-100 text-blue-800',
  };
  return colors[status] || 'bg-gray-100 text-gray-800';
}

/**
 * Get rollout stage badge color
 */
export function getRolloutStageColor(stage: RolloutStage): string {
  const colors: Record<RolloutStage, string> = {
    development: 'bg-yellow-100 text-yellow-800',
    beta: 'bg-purple-100 text-purple-800',
    production: 'bg-green-100 text-green-800',
  };
  return colors[stage] || 'bg-gray-100 text-gray-800';
}

/**
 * Get category icon
 */
export function getCategoryIcon(category: string): string {
  const icons: Record<string, string> = {
    ui: '🎨',
    trading: '📈',
    ml: '🤖',
    assistant: '💬',
    portfolio: '📊',
    security: '🔒',
    general: '⚙️',
  };
  return icons[category] || '⚙️';
}

// ============================================================================
// Custom Hook for Feature Flag Checks
// ============================================================================

/**
 * Simple hook to check if a feature is enabled
 * Usage: const isDarkModeEnabled = useFeature('enable_dark_mode');
 */
export function useFeature(code: string): boolean {
  const { data, isLoading } = useFlagCheck(code);

  // Default to false while loading
  if (isLoading || data === undefined) {
    return false;
  }

  return data;
}

/**
 * Hook to get multiple flag values at once
 * Returns a map of code -> enabled
 */
export function useFeatures(): Record<string, boolean> {
  const { data: evaluations } = useFlagEvaluations();

  if (!evaluations) {
    return {};
  }

  return evaluations.reduce(
    (acc, evaluation) => {
      acc[evaluation.flagCode] = evaluation.enabled;
      return acc;
    },
    {} as Record<string, boolean>
  );
}

// ============================================================================
// Export
// ============================================================================

export const featureFlagsHooks = {
  useFeatureFlags,
  useFlagEvaluations,
  useFlagEvaluation,
  useFlagCheck,
  useCreateFlag,
  useToggleFlag,
  useFeature,
  useFeatures,
  getFlagStatusColor,
  getRolloutStageColor,
  getCategoryIcon,
};

export default featureFlagsHooks;
