// Analytics domain types and interfaces for comprehensive bakery management analytics

export type ReportType = 'sales' | 'production' | 'inventory' | 'financial' | 'customer' | 'performance';
export type ChartType = 'line' | 'bar' | 'pie' | 'area' | 'scatter' | 'doughnut' | 'radar' | 'mixed';
export type ExportFormat = 'pdf' | 'excel' | 'csv' | 'png' | 'svg' | 'json';
export type FilterType = 'date' | 'select' | 'multiselect' | 'range' | 'text' | 'number' | 'boolean';
export type MetricType = 'currency' | 'percentage' | 'number' | 'count' | 'duration' | 'ratio';
export type TimeRange = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth' | 'thisQuarter' | 'lastQuarter' | 'thisYear' | 'lastYear' | 'custom';
export type ComparisonType = 'previous_period' | 'same_period_last_year' | 'target' | 'average' | 'none';

// Base interfaces
export interface BaseAnalyticsEntity {
  id: string;
  name: string;
  description?: string;
  created_at: string;
  updated_at: string;
  created_by?: string;
  tenant_id: string;
}

// Report interfaces
export interface AnalyticsReport extends BaseAnalyticsEntity {
  type: ReportType;
  category: string;
  subcategory?: string;
  config: ReportConfig;
  schedule?: ReportSchedule;
  status: 'active' | 'inactive' | 'archived';
  last_run?: string;
  next_run?: string;
  metrics: ReportMetric[];
  filters: ReportFilter[];
  access_permissions: string[];
  tags: string[];
}

export interface ReportConfig {
  data_source: string;
  refresh_interval: number; // in minutes
  cache_duration: number; // in minutes
  max_records: number;
  default_time_range: TimeRange;
  default_filters: Record<string, any>;
  visualization_type: ChartType;
  custom_sql?: string;
  aggregation_rules: AggregationRule[];
}

export interface ReportSchedule {
  enabled: boolean;
  frequency: 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly';
  time: string; // HH:mm format
  days_of_week?: number[]; // 0-6, Sunday = 0
  day_of_month?: number; // 1-31
  recipients: string[];
  format: ExportFormat;
  include_attachments: boolean;
  custom_message?: string;
}

export interface ReportMetric {
  id: string;
  name: string;
  display_name: string;
  type: MetricType;
  calculation: 'sum' | 'avg' | 'count' | 'min' | 'max' | 'distinct' | 'custom';
  format: string;
  unit?: string;
  decimal_places: number;
  show_comparison: boolean;
  comparison_type?: ComparisonType;
  target_value?: number;
  alert_thresholds?: AlertThreshold[];
  description?: string;
}

export interface AlertThreshold {
  type: 'min' | 'max' | 'range';
  value: number | [number, number];
  severity: 'info' | 'warning' | 'critical';
  message: string;
}

export interface AggregationRule {
  field: string;
  operation: 'group_by' | 'sum' | 'avg' | 'count' | 'min' | 'max';
  alias?: string;
  having_condition?: string;
}

// Chart interfaces
export interface ChartWidget {
  id: string;
  title: string;
  subtitle?: string;
  type: ChartType;
  config: ChartConfig;
  data_source: string;
  filters: ChartFilter[];
  dimensions: ChartDimension;
  refresh_interval?: number;
  last_updated?: string;
  loading?: boolean;
  error?: string;
}

export interface ChartConfig {
  theme: 'light' | 'dark' | 'auto';
  color_scheme: string[];
  show_legend: boolean;
  legend_position: 'top' | 'bottom' | 'left' | 'right';
  show_grid: boolean;
  show_tooltips: boolean;
  animation_enabled: boolean;
  responsive: boolean;
  download_enabled: boolean;
  zoom_enabled: boolean;
  pan_enabled: boolean;
  custom_options?: Record<string, any>;
}

export interface ChartDimension {
  width?: number | string;
  height?: number | string;
  aspect_ratio?: string;
  min_width?: number;
  min_height?: number;
  max_width?: number;
  max_height?: number;
}

export interface ChartFilter {
  id: string;
  field: string;
  operator: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'not_in' | 'like' | 'between';
  value: any;
  display_name: string;
}

export interface ChartDataPoint {
  x: string | number | Date;
  y: number;
  label?: string;
  color?: string;
  metadata?: Record<string, any>;
}

export interface ChartSeries {
  id: string;
  name: string;
  data: ChartDataPoint[];
  type?: ChartType;
  color?: string;
  visible: boolean;
  stack_group?: string;
}

// Filter interfaces
export interface FilterPanel {
  id: string;
  title: string;
  filters: AnalyticsFilter[];
  presets: FilterPreset[];
  active_preset?: string;
  layout: 'horizontal' | 'vertical' | 'grid';
  collapsible: boolean;
  default_collapsed: boolean;
}

export interface AnalyticsFilter {
  id: string;
  field: string;
  display_name: string;
  type: FilterType;
  required: boolean;
  multiple: boolean;
  default_value?: any;
  options?: FilterOption[];
  validation_rules?: FilterValidation[];
  depends_on?: string[]; // Other filter IDs this filter depends on
  placeholder?: string;
  help_text?: string;
  category?: string;
}

export interface FilterOption {
  value: any;
  label: string;
  description?: string;
  icon?: string;
  color?: string;
  disabled?: boolean;
}

export interface FilterValidation {
  rule: 'required' | 'min' | 'max' | 'pattern' | 'custom';
  value?: any;
  message: string;
}

export interface FilterPreset {
  id: string;
  name: string;
  description?: string;
  is_default: boolean;
  is_public: boolean;
  created_by?: string;
  values: Record<string, any>;
  icon?: string;
  tags?: string[];
}

export interface AppliedFilter {
  filter_id: string;
  field: string;
  operator: string;
  value: any;
  display_value?: string;
}

// Export interfaces
export interface ExportOptions {
  format: ExportFormat;
  template?: string;
  include_headers: boolean;
  include_filters: boolean;
  include_summary: boolean;
  date_format: string;
  number_format: string;
  currency_format: string;
  locale: string;
  timezone: string;
  page_size?: 'A4' | 'A3' | 'Letter' | 'Legal';
  orientation?: 'portrait' | 'landscape';
  margins?: ExportMargins;
  watermark?: string;
  password_protected?: boolean;
  password?: string;
  compression_level?: number;
}

export interface ExportMargins {
  top: number;
  right: number;
  bottom: number;
  left: number;
}

export interface ExportJob {
  id: string;
  type: 'report' | 'chart' | 'data';
  format: ExportFormat;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';
  progress: number; // 0-100
  created_at: string;
  started_at?: string;
  completed_at?: string;
  file_size?: number;
  download_url?: string;
  expires_at?: string;
  error_message?: string;
  options: ExportOptions;
  metadata: ExportMetadata;
}

export interface ExportMetadata {
  report_id?: string;
  chart_id?: string;
  filters_applied: AppliedFilter[];
  total_records: number;
  data_range: {
    from: string;
    to: string;
  };
  generated_by: string;
  title: string;
  description?: string;
}

export interface ExportTemplate {
  id: string;
  name: string;
  description?: string;
  format: ExportFormat;
  is_default: boolean;
  is_public: boolean;
  config: ExportTemplateConfig;
  preview_url?: string;
  created_by?: string;
  created_at: string;
}

export interface ExportTemplateConfig {
  header: ExportHeaderConfig;
  footer: ExportFooterConfig;
  styling: ExportStylingConfig;
  layout: ExportLayoutConfig;
  sections: ExportSectionConfig[];
}

export interface ExportHeaderConfig {
  show_logo: boolean;
  logo_url?: string;
  show_title: boolean;
  show_date: boolean;
  show_filters: boolean;
  custom_text?: string;
}

export interface ExportFooterConfig {
  show_page_numbers: boolean;
  show_generated_info: boolean;
  custom_text?: string;
}

export interface ExportStylingConfig {
  font_family: string;
  font_size: number;
  colors: {
    primary: string;
    secondary: string;
    text: string;
    background: string;
    border: string;
  };
  table_style: 'minimal' | 'bordered' | 'striped' | 'compact';
}

export interface ExportLayoutConfig {
  columns: number;
  spacing: number;
  show_grid: boolean;
  section_breaks: boolean;
}

export interface ExportSectionConfig {
  type: 'table' | 'chart' | 'summary' | 'text' | 'spacer';
  title?: string;
  content: any;
  width: number; // percentage
  height?: number;
  order: number;
}

// Bakery-specific analytics interfaces
export interface BakeryMetrics {
  sales: SalesMetrics;
  production: ProductionMetrics;
  inventory: InventoryMetrics;
  financial: FinancialMetrics;
  customer: CustomerMetrics;
  operational: OperationalMetrics;
}

export interface SalesMetrics {
  total_revenue: number;
  total_orders: number;
  average_order_value: number;
  revenue_growth: number;
  order_growth: number;
  conversion_rate: number;
  top_products: ProductPerformance[];
  sales_by_channel: ChannelPerformance[];
  hourly_sales: TimeSeriesData[];
  seasonal_trends: SeasonalData[];
}

export interface ProductionMetrics {
  total_batches: number;
  success_rate: number;
  waste_percentage: number;
  production_efficiency: number;
  quality_score: number;
  capacity_utilization: number;
  production_costs: number;
  batch_cycle_time: number;
  top_recipes: RecipePerformance[];
  quality_trends: TimeSeriesData[];
}

export interface InventoryMetrics {
  total_stock_value: number;
  turnover_rate: number;
  days_of_inventory: number;
  stockout_rate: number;
  waste_value: number;
  carrying_costs: number;
  reorder_efficiency: number;
  supplier_performance: SupplierPerformance[];
  stock_levels: StockLevelData[];
  expiry_alerts: ExpiryAlert[];
}

export interface FinancialMetrics {
  gross_profit: number;
  net_profit: number;
  profit_margin: number;
  cost_of_goods_sold: number;
  operating_expenses: number;
  break_even_point: number;
  cash_flow: number;
  roi: number;
  expense_breakdown: ExpenseCategory[];
  profit_trends: TimeSeriesData[];
}

export interface CustomerMetrics {
  total_customers: number;
  new_customers: number;
  returning_customers: number;
  customer_retention_rate: number;
  customer_lifetime_value: number;
  average_purchase_frequency: number;
  customer_satisfaction: number;
  customer_segments: CustomerSegment[];
  loyalty_program_performance: LoyaltyMetrics[];
}

export interface OperationalMetrics {
  staff_productivity: number;
  equipment_uptime: number;
  energy_consumption: number;
  delivery_performance: number;
  food_safety_score: number;
  compliance_rate: number;
  maintenance_costs: number;
  operational_efficiency: number;
}

// Supporting interfaces
export interface ProductPerformance {
  product_id: string;
  product_name: string;
  category: string;
  quantity_sold: number;
  revenue: number;
  profit_margin: number;
  growth_rate: number;
  stock_turns: number;
}

export interface ChannelPerformance {
  channel: string;
  revenue: number;
  orders: number;
  customers: number;
  conversion_rate: number;
  average_order_value: number;
  growth_rate: number;
}

export interface RecipePerformance {
  recipe_id: string;
  recipe_name: string;
  batches_produced: number;
  success_rate: number;
  average_yield: number;
  cost_per_unit: number;
  quality_score: number;
  profitability: number;
}

export interface SupplierPerformance {
  supplier_id: string;
  supplier_name: string;
  on_time_delivery: number;
  quality_rating: number;
  cost_competitiveness: number;
  total_orders: number;
  total_value: number;
  reliability_score: number;
}

export interface TimeSeriesData {
  date: string;
  value: number;
  label?: string;
  target?: number;
  previous_period?: number;
}

export interface SeasonalData {
  period: string; // "Q1", "Q2", etc. or "Jan", "Feb", etc.
  value: number;
  year: number;
  trend: 'up' | 'down' | 'stable';
  percentage_change: number;
}

export interface StockLevelData {
  item_id: string;
  item_name: string;
  category: string;
  current_stock: number;
  minimum_stock: number;
  maximum_stock: number;
  reorder_point: number;
  stock_status: 'low' | 'normal' | 'high' | 'out_of_stock';
  days_remaining: number;
}

export interface ExpiryAlert {
  item_id: string;
  item_name: string;
  batch_number: string;
  expiry_date: string;
  days_to_expiry: number;
  quantity: number;
  value: number;
  risk_level: 'low' | 'medium' | 'high' | 'critical';
}

export interface ExpenseCategory {
  category: string;
  amount: number;
  percentage: number;
  change_from_previous: number;
  budget_variance: number;
  subcategories?: ExpenseSubcategory[];
}

export interface ExpenseSubcategory {
  name: string;
  amount: number;
  percentage: number;
}

export interface CustomerSegment {
  segment_id: string;
  segment_name: string;
  customer_count: number;
  revenue_contribution: number;
  average_order_value: number;
  purchase_frequency: number;
  retention_rate: number;
  growth_rate: number;
}

export interface LoyaltyMetrics {
  program_name: string;
  active_members: number;
  enrollment_rate: number;
  redemption_rate: number;
  points_issued: number;
  points_redeemed: number;
  revenue_from_members: number;
  member_retention: number;
}

// Component prop types
export interface ReportsTableProps {
  reports?: AnalyticsReport[];
  loading?: boolean;
  error?: string;
  selectedReports?: string[];
  onSelectionChange?: (selectedIds: string[]) => void;
  onReportClick?: (report: AnalyticsReport) => void;
  onEditReport?: (report: AnalyticsReport) => void;
  onDeleteReport?: (reportId: string) => void;
  onScheduleReport?: (report: AnalyticsReport) => void;
  onShareReport?: (report: AnalyticsReport) => void;
  onExportReport?: (report: AnalyticsReport, format: ExportFormat) => void;
  filters?: AppliedFilter[];
  onFiltersChange?: (filters: AppliedFilter[]) => void;
  sortable?: boolean;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    onChange: (page: number, pageSize: number) => void;
  };
  bulkActions?: boolean;
  customActions?: CustomAction[];
  tableConfig?: ReportsTableConfig;
}

export interface ChartWidgetProps {
  widget: ChartWidget;
  data?: ChartSeries[];
  loading?: boolean;
  error?: string;
  onConfigChange?: (config: Partial<ChartConfig>) => void;
  onFiltersChange?: (filters: ChartFilter[]) => void;
  onRefresh?: () => void;
  onExport?: (format: ExportFormat) => void;
  onFullscreen?: () => void;
  interactive?: boolean;
  showControls?: boolean;
  showTitle?: boolean;
  showSubtitle?: boolean;
  className?: string;
}

export interface FilterPanelProps {
  panel: FilterPanel;
  appliedFilters?: AppliedFilter[];
  onFiltersChange?: (filters: AppliedFilter[]) => void;
  onPresetSelect?: (presetId: string) => void;
  onPresetSave?: (preset: Omit<FilterPreset, 'id'>) => void;
  onPresetDelete?: (presetId: string) => void;
  onReset?: () => void;
  loading?: boolean;
  disabled?: boolean;
  compact?: boolean;
  showPresets?: boolean;
  showReset?: boolean;
  className?: string;
}

export interface ExportOptionsProps {
  type: 'report' | 'chart' | 'data';
  title: string;
  description?: string;
  availableFormats?: ExportFormat[];
  templates?: ExportTemplate[];
  onExport?: (options: ExportOptions) => void;
  onSchedule?: (schedule: ReportSchedule) => void;
  loading?: boolean;
  disabled?: boolean;
  showScheduling?: boolean;
  showTemplates?: boolean;
  showAdvanced?: boolean;
  defaultOptions?: Partial<ExportOptions>;
  className?: string;
}

export interface CustomAction {
  key: string;
  label: string;
  icon?: React.ReactNode;
  onClick: (selectedItems: any[]) => void;
  disabled?: (selectedItems: any[]) => boolean;
  visible?: (selectedItems: any[]) => boolean;
  type?: 'default' | 'primary' | 'danger' | 'success' | 'warning';
}

export interface ReportsTableConfig {
  showSearch?: boolean;
  showFilters?: boolean;
  showExport?: boolean;
  showColumns?: boolean;
  showRefresh?: boolean;
  showBulkActions?: boolean;
  defaultPageSize?: number;
  stickyHeader?: boolean;
  compactMode?: boolean;
  customColumns?: TableColumn[];
}

export interface TableColumn {
  key: string;
  title: string;
  dataIndex?: string;
  sortable?: boolean;
  filterable?: boolean;
  searchable?: boolean;
  width?: number | string;
  align?: 'left' | 'center' | 'right';
  render?: (value: any, record: any) => React.ReactNode;
  format?: 'date' | 'currency' | 'number' | 'percentage' | 'text';
  fixed?: 'left' | 'right';
  ellipsis?: boolean;
  copyable?: boolean;
  editable?: boolean;
}

// API response types
export interface AnalyticsApiResponse<T = any> {
  success: boolean;
  data: T;
  message?: string;
  metadata?: {
    total_records: number;
    filtered_records: number;
    execution_time: number;
    cache_hit: boolean;
    generated_at: string;
  };
}

export interface ReportsListResponse extends AnalyticsApiResponse<AnalyticsReport[]> {
  pagination: {
    current_page: number;
    total_pages: number;
    page_size: number;
    total_records: number;
  };
  filters_applied: AppliedFilter[];
  sort_applied?: {
    field: string;
    order: 'asc' | 'desc';
  };
}

export interface ChartDataResponse extends AnalyticsApiResponse<ChartSeries[]> {
  chart_config: ChartConfig;
  time_range: {
    from: string;
    to: string;
  };
  filters_applied: AppliedFilter[];
  data_source: string;
}

export interface ExportJobResponse extends AnalyticsApiResponse<ExportJob> {
  estimated_completion: string;
  queue_position?: number;
}