/**
 * useSubscription Hook
 *
 * Fetches subscription data and usage forecast with automatic refresh.
 * Combines current subscription info with predictive analytics.
 */

import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { subscriptionService } from '@/api/services/subscription';
import type { SubscriptionTier } from '@/api/types/subscription';
import { useTenantId } from './useTenantId';

// Type definitions
interface UsageMetric {
  current: number;
  limit: number | null;
  trend?: number[];
  predictedBreachDate?: string | null;
  daysUntilBreach?: number | null;
  status?: 'safe' | 'warning' | 'critical' | 'unlimited';
}

interface SubscriptionData {
  tier: SubscriptionTier;
  billing_cycle: 'monthly' | 'yearly';
  monthly_price: number;
  yearly_price: number;
  renewal_date: string;
  trial_ends_at?: string;
  limits: {
    users: number | null;
    locations: number | null;
    products: number | null;
    recipes: number | null;
    suppliers: number | null;
    trainingJobsPerDay: number | null;
    forecastsPerDay: number | null;
    storageGB: number | null;
  };
  availablePlans: any; // Your plan metadata type
}

interface UsageData {
  products: UsageMetric;
  users: UsageMetric;
  locations: UsageMetric;
  trainingJobs: UsageMetric;
  forecasts: UsageMetric;
  storage: UsageMetric;
  highUsageMetrics: string[]; // List of metrics at >80%
}

interface ForecastData {
  tenant_id: string;
  forecasted_at: string;
  metrics: Array<{
    metric: string;
    label: string;
    current: number;
    limit: number | null;
    unit: string;
    daily_growth_rate: number | null;
    predicted_breach_date: string | null;
    days_until_breach: number | null;
    usage_percentage: number;
    status: string;
    trend_data: Array<{ date: string; value: number }>;
  }>;
}

export const useSubscription = () => {
  // Use centralized tenant ID hook from tenant store
  const tenantId = useTenantId();

  // Fetch current subscription
  const {
    data: subscription,
    isLoading: isLoadingSubscription,
    error: subscriptionError
  } = useQuery<SubscriptionData>({
    queryKey: ['subscription', tenantId],
    queryFn: () => subscriptionService.getCurrentSubscription(tenantId),
    enabled: !!tenantId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchOnWindowFocus: false,
  });

  // Fetch usage forecast
  const {
    data: forecast,
    isLoading: isLoadingForecast,
    error: forecastError
  } = useQuery<ForecastData>({
    queryKey: ['usage-forecast', tenantId],
    queryFn: () => subscriptionService.getUsageForecast(tenantId),
    enabled: !!tenantId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchInterval: 5 * 60 * 1000, // Auto-refresh every 5 minutes
    refetchOnWindowFocus: true,
  });

  // Transform forecast data into structured usage object
  const usage: UsageData = React.useMemo(() => {
    if (!forecast) {
      return {
        products: { current: 0, limit: null },
        users: { current: 0, limit: null },
        locations: { current: 0, limit: null },
        trainingJobs: { current: 0, limit: null },
        forecasts: { current: 0, limit: null },
        storage: { current: 0, limit: null },
        highUsageMetrics: [],
      };
    }

    const getMetric = (metricName: string): UsageMetric => {
      const metric = forecast.metrics.find(m => m.metric === metricName);
      if (!metric) {
        return { current: 0, limit: null };
      }

      return {
        current: metric.current,
        limit: metric.limit,
        trend: metric.trend_data.map(d => d.value),
        predictedBreachDate: metric.predicted_breach_date,
        daysUntilBreach: metric.days_until_breach,
        status: metric.status as any,
      };
    };

    // Identify high usage metrics (>80%)
    const highUsageMetrics = forecast.metrics
      .filter(m => m.usage_percentage >= 80 && m.limit !== null && m.limit !== -1)
      .map(m => m.metric);

    return {
      products: getMetric('products'),
      users: getMetric('users'),
      locations: getMetric('locations'),
      trainingJobs: getMetric('training_jobs'),
      forecasts: getMetric('forecasts'),
      storage: getMetric('storage'),
      highUsageMetrics,
    };
  }, [forecast]);

  return {
    subscription,
    usage,
    forecast,
    isLoading: isLoadingSubscription || isLoadingForecast,
    error: subscriptionError || forecastError,
  };
};
