/**
 * Analytics Types for LocalGreenChain
 * Defines all types for the Advanced Analytics Dashboard
 */

// Time range options for analytics queries
export type TimeRange = '7d' | '30d' | '90d' | '365d' | 'all';

export interface DateRange {
  start: Date;
  end: Date;
}

// Generic data point for time series
export interface TimeSeriesDataPoint {
  timestamp: string;
  value: number;
  label?: string;
}

// Analytics overview metrics
export interface AnalyticsOverview {
  totalPlants: number;
  plantsRegisteredToday: number;
  plantsRegisteredThisWeek: number;
  plantsRegisteredThisMonth: number;
  totalTransportEvents: number;
  totalCarbonKg: number;
  totalFoodMiles: number;
  activeUsers: number;
  growthRate: number;
  trendsData: TrendData[];
}

// Trend direction indicator
export type TrendDirection = 'up' | 'down' | 'stable';

export interface TrendData {
  metric: string;
  currentValue: number;
  previousValue: number;
  change: number;
  changePercent: number;
  direction: TrendDirection;
  period: string;
}

// Plant analytics
export interface PlantAnalytics {
  totalPlants: number;
  plantsBySpecies: SpeciesDistribution[];
  plantsByGeneration: GenerationDistribution[];
  registrationsTrend: TimeSeriesDataPoint[];
  averageLineageDepth: number;
  topGrowers: GrowerStats[];
  recentRegistrations: PlantRegistration[];
}

export interface SpeciesDistribution {
  species: string;
  count: number;
  percentage: number;
  trend: TrendDirection;
}

export interface GenerationDistribution {
  generation: number;
  count: number;
  percentage: number;
}

export interface GrowerStats {
  userId: string;
  name: string;
  totalPlants: number;
  totalSpecies: number;
  averageGeneration: number;
}

export interface PlantRegistration {
  id: string;
  name: string;
  species: string;
  registeredAt: string;
  generation: number;
}

// Transport analytics
export interface TransportAnalytics {
  totalEvents: number;
  totalDistanceKm: number;
  totalCarbonKg: number;
  carbonSavedKg: number;
  eventsByType: TransportEventDistribution[];
  eventsByMethod: TransportMethodDistribution[];
  dailyStats: DailyTransportStats[];
  averageDistancePerEvent: number;
  mostEfficientRoutes: EfficientRoute[];
  carbonTrend: TimeSeriesDataPoint[];
}

export interface TransportEventDistribution {
  eventType: string;
  count: number;
  percentage: number;
  carbonKg: number;
}

export interface TransportMethodDistribution {
  method: string;
  count: number;
  percentage: number;
  distanceKm: number;
  carbonKg: number;
  efficiency: number;
}

export interface DailyTransportStats {
  date: string;
  eventCount: number;
  distanceKm: number;
  carbonKg: number;
}

export interface EfficientRoute {
  from: string;
  to: string;
  method: string;
  distanceKm: number;
  carbonKg: number;
  frequency: number;
}

// Vertical farm analytics
export interface FarmAnalytics {
  totalFarms: number;
  totalZones: number;
  activeBatches: number;
  completedBatches: number;
  averageYieldKg: number;
  resourceUsage: ResourceUsageStats;
  performanceByZone: ZonePerformance[];
  batchCompletionTrend: TimeSeriesDataPoint[];
  yieldPredictions: YieldPrediction[];
  topPerformingCrops: CropPerformance[];
}

export interface ResourceUsageStats {
  waterLiters: number;
  energyKwh: number;
  nutrientsKg: number;
  waterEfficiency: number;
  energyEfficiency: number;
}

export interface ZonePerformance {
  zoneId: string;
  zoneName: string;
  currentCrop: string;
  healthScore: number;
  yieldKg: number;
  efficiency: number;
}

export interface YieldPrediction {
  cropType: string;
  predictedYieldKg: number;
  confidence: number;
  harvestDate: string;
}

export interface CropPerformance {
  cropType: string;
  averageYieldKg: number;
  growthDays: number;
  successRate: number;
  batches: number;
}

// Sustainability analytics
export interface SustainabilityAnalytics {
  overallScore: number;
  carbonFootprint: CarbonMetrics;
  foodMiles: FoodMilesMetrics;
  waterUsage: WaterMetrics;
  localProduction: LocalProductionMetrics;
  goals: SustainabilityGoal[];
  trends: SustainabilityTrend[];
}

export interface CarbonMetrics {
  totalEmittedKg: number;
  totalSavedKg: number;
  netImpactKg: number;
  reductionPercentage: number;
  equivalentTrees: number;
  monthlyTrend: TimeSeriesDataPoint[];
}

export interface FoodMilesMetrics {
  totalMiles: number;
  averageMilesPerPlant: number;
  savedMiles: number;
  localPercentage: number;
  monthlyTrend: TimeSeriesDataPoint[];
}

export interface WaterMetrics {
  totalUsedLiters: number;
  savedLiters: number;
  efficiencyScore: number;
  perKgProduce: number;
}

export interface LocalProductionMetrics {
  localCount: number;
  totalCount: number;
  percentage: number;
  trend: TrendDirection;
}

export interface SustainabilityGoal {
  id: string;
  name: string;
  target: number;
  current: number;
  unit: string;
  progress: number;
  deadline: string;
  status: 'on_track' | 'at_risk' | 'behind';
}

export interface SustainabilityTrend {
  metric: string;
  values: TimeSeriesDataPoint[];
}

// Export options
export interface ExportOptions {
  format: 'csv' | 'pdf' | 'json';
  dateRange: DateRange;
  sections: string[];
  includeCharts: boolean;
}

export interface ExportResult {
  filename: string;
  mimeType: string;
  data: string;
  generatedAt: string;
}

// Dashboard configuration
export interface DashboardConfig {
  refreshInterval: number;
  defaultTimeRange: TimeRange;
  visibleWidgets: string[];
  layout: 'grid' | 'list';
}

// KPI Card configuration
export interface KPICardData {
  id: string;
  title: string;
  value: number | string;
  unit?: string;
  change?: number;
  changePercent?: number;
  trend: TrendDirection;
  color: 'green' | 'blue' | 'purple' | 'orange' | 'red' | 'teal';
  icon?: string;
}

// Chart configuration
export interface ChartConfig {
  title: string;
  type: 'line' | 'bar' | 'pie' | 'area' | 'heatmap' | 'gauge';
  data: any[];
  xKey?: string;
  yKey?: string;
  colors?: string[];
  showLegend?: boolean;
  showGrid?: boolean;
  height?: number;
}

// Filter state for analytics
export interface AnalyticsFilters {
  timeRange: TimeRange;
  dateRange?: DateRange;
  species?: string[];
  regions?: string[];
  transportMethods?: string[];
  farmIds?: string[];
}

// Aggregation types
export type AggregationType = 'sum' | 'avg' | 'min' | 'max' | 'count';
export type GroupByPeriod = 'hour' | 'day' | 'week' | 'month' | 'year';

export interface AggregationConfig {
  metric: string;
  aggregation: AggregationType;
  groupBy?: GroupByPeriod;
  filters?: Record<string, any>;
}
