/**
 * Dashboard React Query hooks
 * Aggregates data from multiple services for dashboard metrics
 */

import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { useSalesAnalytics } from './sales';
import { useOrdersDashboard } from './orders';
import { inventoryService } from '../services/inventory';
import { getAlertAnalytics } from '../services/alert_analytics';
import { getSustainabilityWidgetData } from '../services/sustainability';
import { ApiError } from '../client/apiClient';
import type { InventoryDashboardSummary } from '../types/inventory';
import type { AlertAnalytics } from '../services/alert_analytics';
import type { SalesAnalytics } from '../types/sales';
import type { OrdersDashboardSummary } from '../types/orders';
import type { SustainabilityWidgetData } from '../types/sustainability';

export interface DashboardStats {
  // Alert metrics
  activeAlerts: number;
  criticalAlerts: number;

  // Order metrics
  pendingOrders: number;
  ordersToday: number;
  ordersTrend: number; // percentage change

  // Sales metrics
  salesToday: number;
  salesTrend: number; // percentage change
  salesCurrency: string;

  // Inventory metrics
  criticalStock: number;
  lowStockCount: number;
  outOfStockCount: number;
  expiringSoon: number;

  // Production metrics
  productsSoldToday: number;
  productsSoldTrend: number;

  // Sustainability metrics
  wasteReductionPercentage?: number;
  monthlySavingsEur?: number;

  // Data freshness
  lastUpdated: string;
}

interface AggregatedDashboardData {
  alerts?: AlertAnalytics;
  orders?: OrdersDashboardSummary;
  sales?: SalesAnalytics;
  inventory?: InventoryDashboardSummary;
  sustainability?: SustainabilityWidgetData;
}

// Query Keys
export const dashboardKeys = {
  all: ['dashboard'] as const,
  stats: (tenantId: string) => [...dashboardKeys.all, 'stats', tenantId] as const,
  inventory: (tenantId: string) => [...dashboardKeys.all, 'inventory', tenantId] as const,
} as const;

/**
 * Fetch inventory dashboard summary
 */
export const useInventoryDashboard = (
  tenantId: string,
  options?: Omit<UseQueryOptions<InventoryDashboardSummary, ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<InventoryDashboardSummary, ApiError>({
    queryKey: dashboardKeys.inventory(tenantId),
    queryFn: () => inventoryService.getDashboardSummary(tenantId),
    enabled: !!tenantId,
    staleTime: 30 * 1000, // 30 seconds
    ...options,
  });
};

/**
 * Fetch alert analytics
 */
export const useAlertAnalytics = (
  tenantId: string,
  days: number = 7,
  options?: Omit<UseQueryOptions<AlertAnalytics, ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<AlertAnalytics, ApiError>({
    queryKey: ['alerts', 'analytics', tenantId, days],
    queryFn: () => getAlertAnalytics(tenantId, days),
    enabled: !!tenantId,
    staleTime: 30 * 1000, // 30 seconds
    ...options,
  });
};

/**
 * Calculate percentage change between two values
 */
function calculateTrend(current: number, previous: number): number {
  if (previous === 0) return current > 0 ? 100 : 0;
  return Math.round(((current - previous) / previous) * 100);
}

/**
 * Calculate today's sales from sales records (REMOVED - Professional/Enterprise tier feature)
 * Basic tier users don't get sales analytics on dashboard
 */
function calculateTodaySales(): { amount: number; trend: number; productsSold: number; productsTrend: number } {
  // Return zero values - sales analytics not available for basic tier
  return { amount: 0, trend: 0, productsSold: 0, productsTrend: 0 };
}

/**
 * Calculate orders metrics
 */
function calculateOrdersMetrics(ordersData?: OrdersDashboardSummary): { pending: number; today: number; trend: number } {
  if (!ordersData) {
    return { pending: 0, today: 0, trend: 0 };
  }

  const pendingCount = ordersData.pending_orders || 0;
  const todayCount = ordersData.total_orders_today || 0;

  return {
    pending: pendingCount,
    today: todayCount,
    trend: 0, // Trend calculation removed - needs historical data
  };
}

/**
 * Aggregate dashboard data from all services
 * NOTE: Sales analytics removed - Professional/Enterprise tier feature
 */
function aggregateDashboardStats(data: AggregatedDashboardData): DashboardStats {
  const sales = calculateTodaySales(); // Returns zeros for basic tier
  const orders = calculateOrdersMetrics(data.orders);

  const criticalStockCount =
    (data.inventory?.low_stock_items || 0) +
    (data.inventory?.out_of_stock_items || 0);

  return {
    // Alerts
    activeAlerts: data.alerts?.activeAlerts || 0,
    criticalAlerts: data.alerts?.totalAlerts || 0,

    // Orders
    pendingOrders: orders.pending,
    ordersToday: orders.today,
    ordersTrend: orders.trend,

    // Sales (REMOVED - not available for basic tier)
    salesToday: 0,
    salesTrend: 0,
    salesCurrency: '€',

    // Inventory
    criticalStock: criticalStockCount,
    lowStockCount: data.inventory?.low_stock_items || 0,
    outOfStockCount: data.inventory?.out_of_stock_items || 0,
    expiringSoon: data.inventory?.expiring_soon_items || 0,

    // Products (REMOVED - not available for basic tier)
    productsSoldToday: 0,
    productsSoldTrend: 0,

    // Sustainability
    wasteReductionPercentage: data.sustainability?.waste_reduction_percentage,
    monthlySavingsEur: data.sustainability?.financial_savings_eur,

    // Metadata
    lastUpdated: new Date().toISOString(),
  };
}

/**
 * Main hook to fetch aggregated dashboard statistics
 * Combines data from multiple services into a single cohesive dashboard view
 */
export const useDashboardStats = (
  tenantId: string,
  options?: Omit<UseQueryOptions<DashboardStats, ApiError>, 'queryKey' | 'queryFn'>
) => {
  // Get today's date range for sales
  const today = new Date();
  const todayStr = today.toISOString().split('T')[0];
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const yesterdayStr = yesterday.toISOString().split('T')[0];

  return useQuery<DashboardStats, ApiError>({
    queryKey: dashboardKeys.stats(tenantId),
    queryFn: async () => {
      // Fetch all data in parallel (REMOVED sales analytics - Professional/Enterprise tier only)
      const [alertsData, ordersData, inventoryData, sustainabilityData] = await Promise.allSettled([
        getAlertAnalytics(tenantId, 7),
        // Note: OrdersService methods are static
        import('../services/orders').then(({ OrdersService }) =>
          OrdersService.getDashboardSummary(tenantId)
        ),
        inventoryService.getDashboardSummary(tenantId),
        getSustainabilityWidgetData(tenantId, 30), // 30 days for monthly savings
      ]);

      // Extract data or use undefined for failed requests
      const aggregatedData: AggregatedDashboardData = {
        alerts: alertsData.status === 'fulfilled' ? alertsData.value : undefined,
        orders: ordersData.status === 'fulfilled' ? ordersData.value : undefined,
        sales: undefined, // REMOVED - Professional/Enterprise tier only
        inventory: inventoryData.status === 'fulfilled' ? inventoryData.value : undefined,
        sustainability: sustainabilityData.status === 'fulfilled' ? sustainabilityData.value : undefined,
      };

      // Log any failures for debugging
      if (alertsData.status === 'rejected') {
        console.warn('[Dashboard] Failed to fetch alerts:', alertsData.reason);
      }
      if (ordersData.status === 'rejected') {
        console.warn('[Dashboard] Failed to fetch orders:', ordersData.reason);
      }
      if (inventoryData.status === 'rejected') {
        console.warn('[Dashboard] Failed to fetch inventory:', inventoryData.reason);
      }
      if (sustainabilityData.status === 'rejected') {
        console.warn('[Dashboard] Failed to fetch sustainability:', sustainabilityData.reason);
      }

      return aggregateDashboardStats(aggregatedData);
    },
    enabled: !!tenantId,
    staleTime: 30 * 1000, // 30 seconds
    refetchInterval: 60 * 1000, // Auto-refresh every minute
    retry: 2, // Retry failed requests twice
    retryDelay: 1000, // Wait 1s between retries
    ...options,
  });
};
