// ================================================================
// frontend/src/api/hooks/newDashboard.ts
// ================================================================
/**
 * API Hooks for JTBD-Aligned Dashboard
 *
 * Provides data fetching for the redesigned bakery dashboard with focus on:
 * - Health status
 * - Action queue
 * - Orchestration summary
 * - Production timeline
 * - Key insights
 */

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

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

export interface HealthChecklistItem {
  icon: 'check' | 'warning' | 'alert';
  text: string;
  actionRequired: boolean;
}

export interface BakeryHealthStatus {
  status: 'green' | 'yellow' | 'red';
  headline: string;
  lastOrchestrationRun: string | null;
  nextScheduledRun: string;
  checklistItems: HealthChecklistItem[];
  criticalIssues: number;
  pendingActions: number;
}

export interface ReasoningInputs {
  customerOrders: number;
  historicalDemand: boolean;
  inventoryLevels: boolean;
  aiInsights: boolean;
}

export interface PurchaseOrderSummary {
  supplierName: string;
  itemCategories: string[];
  totalAmount: number;
}

export interface ProductionBatchSummary {
  productName: string;
  quantity: number;
  readyByTime: string;
}

export interface OrchestrationSummary {
  runTimestamp: string | null;
  runNumber: number | null;
  status: string;
  purchaseOrdersCreated: number;
  purchaseOrdersSummary: PurchaseOrderSummary[];
  productionBatchesCreated: number;
  productionBatchesSummary: ProductionBatchSummary[];
  reasoningInputs: ReasoningInputs;
  userActionsRequired: number;
  durationSeconds: number | null;
  aiAssisted: boolean;
  message?: string;
}

export interface ActionButton {
  label: string;
  type: 'primary' | 'secondary' | 'tertiary';
  action: string;
}

export interface ActionItem {
  id: string;
  type: string;
  urgency: 'critical' | 'important' | 'normal';
  title: string;
  subtitle: string;
  reasoning?: string; // Deprecated: Use reasoning_data instead
  consequence?: string; // Deprecated: Use reasoning_data instead
  reasoning_data?: any; // Structured reasoning data for i18n translation
  amount?: number;
  currency?: string;
  actions: ActionButton[];
  estimatedTimeMinutes: number;
}

export interface ActionQueue {
  actions: ActionItem[];
  totalActions: number;
  criticalCount: number;
  importantCount: number;
}

export interface ProductionTimelineItem {
  id: string;
  batchNumber: string;
  productName: string;
  quantity: number;
  unit: string;
  plannedStartTime: string | null;
  plannedEndTime: string | null;
  actualStartTime: string | null;
  status: string;
  statusIcon: string;
  statusText: string;
  progress: number;
  readyBy: string | null;
  priority: string;
  reasoning?: string; // Deprecated: Use reasoning_data instead
  reasoning_data?: any; // Structured reasoning data for i18n translation
}

export interface ProductionTimeline {
  timeline: ProductionTimelineItem[];
  totalBatches: number;
  completedBatches: number;
  inProgressBatches: number;
  pendingBatches: number;
}

export interface InsightCard {
  label: string;
  value: string;
  detail: string;
  color: 'green' | 'amber' | 'red';
}

export interface Insights {
  savings: InsightCard;
  inventory: InsightCard;
  waste: InsightCard;
  deliveries: InsightCard;
}

// ============================================================
// Hooks
// ============================================================

/**
 * Get bakery health status
 *
 * This is the top-level health indicator showing if the bakery is running smoothly.
 * Updates every 30 seconds to keep status fresh.
 */
export function useBakeryHealthStatus(tenantId: string) {
  return useQuery<BakeryHealthStatus>({
    queryKey: ['bakery-health-status', tenantId],
    queryFn: async () => {
      return await apiClient.get(
        `/tenants/${tenantId}/dashboard/health-status`
      );
    },
    enabled: !!tenantId, // Only fetch when tenantId is available
    refetchInterval: 30000, // Refresh every 30 seconds
    staleTime: 20000, // Consider stale after 20 seconds
    retry: 2,
  });
}

/**
 * Get orchestration summary
 *
 * Shows what the automated system did (transparency for trust building).
 */
export function useOrchestrationSummary(tenantId: string, runId?: string) {
  return useQuery<OrchestrationSummary>({
    queryKey: ['orchestration-summary', tenantId, runId],
    queryFn: async () => {
      const params = runId ? { run_id: runId } : {};
      return await apiClient.get(
        `/tenants/${tenantId}/dashboard/orchestration-summary`,
        { params }
      );
    },
    enabled: !!tenantId, // Only fetch when tenantId is available
    staleTime: 60000, // Summary doesn't change often
    retry: 2,
  });
}

/**
 * Get action queue
 *
 * Prioritized list of what requires user attention right now.
 * This is the core JTBD dashboard feature.
 */
export function useActionQueue(tenantId: string) {
  return useQuery<ActionQueue>({
    queryKey: ['action-queue', tenantId],
    queryFn: async () => {
      return await apiClient.get(
        `/tenants/${tenantId}/dashboard/action-queue`
      );
    },
    enabled: !!tenantId, // Only fetch when tenantId is available
    refetchInterval: 60000, // Refresh every minute
    staleTime: 30000,
    retry: 2,
  });
}

/**
 * Get production timeline
 *
 * Shows today's production schedule in chronological order.
 */
export function useProductionTimeline(tenantId: string) {
  return useQuery<ProductionTimeline>({
    queryKey: ['production-timeline', tenantId],
    queryFn: async () => {
      return await apiClient.get(
        `/tenants/${tenantId}/dashboard/production-timeline`
      );
    },
    enabled: !!tenantId, // Only fetch when tenantId is available
    refetchInterval: 60000, // Refresh every minute
    staleTime: 30000,
    retry: 2,
  });
}

/**
 * Get key insights
 *
 * Glanceable metrics on savings, inventory, waste, and deliveries.
 */
export function useInsights(tenantId: string) {
  return useQuery<Insights>({
    queryKey: ['dashboard-insights', tenantId],
    queryFn: async () => {
      return await apiClient.get(
        `/tenants/${tenantId}/dashboard/insights`
      );
    },
    enabled: !!tenantId, // Only fetch when tenantId is available
    refetchInterval: 120000, // Refresh every 2 minutes
    staleTime: 60000,
    retry: 2,
  });
}

// ============================================================
// Action Mutations
// ============================================================

/**
 * Approve a purchase order from the action queue
 */
export function useApprovePurchaseOrder() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tenantId, poId }: { tenantId: string; poId: string }) => {
      const response = await apiClient.post(
        `/procurement/tenants/${tenantId}/purchase-orders/${poId}/approve`
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: ['action-queue', variables.tenantId] });
      queryClient.invalidateQueries({ queryKey: ['bakery-health-status', variables.tenantId] });
      queryClient.invalidateQueries({ queryKey: ['orchestration-summary', variables.tenantId] });
    },
  });
}

/**
 * Dismiss an alert from the action queue
 */
export function useDismissAlert() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tenantId, alertId }: { tenantId: string; alertId: string }) => {
      const response = await apiClient.post(
        `/alert-processor/tenants/${tenantId}/alerts/${alertId}/dismiss`
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['action-queue', variables.tenantId] });
      queryClient.invalidateQueries({ queryKey: ['bakery-health-status', variables.tenantId] });
    },
  });
}

/**
 * Start a production batch
 */
export function useStartProductionBatch() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tenantId, batchId }: { tenantId: string; batchId: string }) => {
      const response = await apiClient.post(
        `/production/tenants/${tenantId}/production-batches/${batchId}/start`
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['production-timeline', variables.tenantId] });
      queryClient.invalidateQueries({ queryKey: ['bakery-health-status', variables.tenantId] });
    },
  });
}

/**
 * Pause a production batch
 */
export function usePauseProductionBatch() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tenantId, batchId }: { tenantId: string; batchId: string }) => {
      const response = await apiClient.post(
        `/production/tenants/${tenantId}/production-batches/${batchId}/pause`
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['production-timeline', variables.tenantId] });
      queryClient.invalidateQueries({ queryKey: ['bakery-health-status', variables.tenantId] });
    },
  });
}
