// Widget Library for Custom Report Builder
// Predefined widgets that can be used in custom reports and dashboards

export type WidgetCategory = 'metric' | 'chart' | 'table' | 'text' | 'filter' | 'custom';
export type WidgetType = 
  | 'kpi_card' 
  | 'sparkline' 
  | 'gauge' 
  | 'line_chart' 
  | 'bar_chart' 
  | 'pie_chart' 
  | 'donut_chart'
  | 'area_chart' 
  | 'scatter_chart'
  | 'radar_chart'
  | 'data_table' 
  | 'summary_table'
  | 'text_block' 
  | 'header'
  | 'date_filter' 
  | 'dropdown_filter'
  | 'comparison_card'
  | 'trend_indicator'
  | 'progress_bar'
  | 'heatmap'
  | 'treemap';

export interface WidgetDefinition {
  key: string;
  name: string;
  description: string;
  category: WidgetCategory;
  widgetType: WidgetType;
  icon: string;
  dataRequirements: {
    metrics?: string[];
    dimensions?: string[];
    minDataPoints?: number;
    maxDataPoints?: number;
  };
  defaultConfig: Record<string, unknown>;
  configSchema: ConfigProperty[];
  defaultSize: { w: number; h: number };
  minSize?: { w: number; h: number };
  maxSize?: { w: number; h: number };
}

export interface ConfigProperty {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select' | 'color' | 'multiselect';
  options?: { value: string; label: string }[];
  defaultValue?: unknown;
  required?: boolean;
}

// ============================================
// METRIC WIDGETS
// ============================================

const metricWidgets: WidgetDefinition[] = [
  {
    key: 'kpi_card',
    name: 'KPI Card',
    description: 'Display a single key metric with optional comparison',
    category: 'metric',
    widgetType: 'kpi_card',
    icon: 'Hash',
    dataRequirements: { metrics: ['value'], maxDataPoints: 1 },
    defaultConfig: {
      title: 'Metric',
      prefix: '',
      suffix: '',
      format: 'number',
      showTrend: true,
      trendPeriod: 'vs_prior',
      color: 'cyan',
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string', required: true },
      { key: 'prefix', label: 'Prefix (e.g., $)', type: 'string' },
      { key: 'suffix', label: 'Suffix (e.g., %)', type: 'string' },
      { key: 'format', label: 'Format', type: 'select', options: [
        { value: 'number', label: 'Number' },
        { value: 'currency', label: 'Currency' },
        { value: 'percentage', label: 'Percentage' },
        { value: 'compact', label: 'Compact (1.2K)' },
      ]},
      { key: 'showTrend', label: 'Show Trend', type: 'boolean', defaultValue: true },
      { key: 'color', label: 'Accent Color', type: 'select', options: [
        { value: 'cyan', label: 'Cyan' },
        { value: 'purple', label: 'Purple' },
        { value: 'green', label: 'Green' },
        { value: 'amber', label: 'Amber' },
        { value: 'red', label: 'Red' },
      ]},
    ],
    defaultSize: { w: 2, h: 1 },
    minSize: { w: 1, h: 1 },
  },
  {
    key: 'sparkline',
    name: 'Sparkline',
    description: 'Compact trend line for quick visualization',
    category: 'metric',
    widgetType: 'sparkline',
    icon: 'Activity',
    dataRequirements: { metrics: ['value'], minDataPoints: 5 },
    defaultConfig: {
      title: 'Trend',
      showValue: true,
      color: 'cyan',
      filled: false,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showValue', label: 'Show Current Value', type: 'boolean', defaultValue: true },
      { key: 'color', label: 'Line Color', type: 'color' },
      { key: 'filled', label: 'Fill Area', type: 'boolean' },
    ],
    defaultSize: { w: 2, h: 1 },
  },
  {
    key: 'gauge',
    name: 'Gauge',
    description: 'Circular progress indicator with target',
    category: 'metric',
    widgetType: 'gauge',
    icon: 'Gauge',
    dataRequirements: { metrics: ['value', 'target'] },
    defaultConfig: {
      title: 'Progress',
      minValue: 0,
      maxValue: 100,
      thresholds: [{ value: 50, color: 'amber' }, { value: 80, color: 'green' }],
      showTarget: true,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'minValue', label: 'Min Value', type: 'number', defaultValue: 0 },
      { key: 'maxValue', label: 'Max Value', type: 'number', defaultValue: 100 },
      { key: 'showTarget', label: 'Show Target', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 2, h: 2 },
  },
  {
    key: 'comparison_card',
    name: 'Comparison Card',
    description: 'Compare two values with variance',
    category: 'metric',
    widgetType: 'comparison_card',
    icon: 'ArrowLeftRight',
    dataRequirements: { metrics: ['current', 'comparison'] },
    defaultConfig: {
      title: 'Comparison',
      currentLabel: 'Current',
      comparisonLabel: 'Prior',
      showPercentage: true,
      invertColors: false,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'currentLabel', label: 'Current Label', type: 'string' },
      { key: 'comparisonLabel', label: 'Comparison Label', type: 'string' },
      { key: 'showPercentage', label: 'Show % Change', type: 'boolean', defaultValue: true },
      { key: 'invertColors', label: 'Invert Colors (red=good)', type: 'boolean' },
    ],
    defaultSize: { w: 2, h: 1 },
  },
  {
    key: 'progress_bar',
    name: 'Progress Bar',
    description: 'Horizontal progress indicator',
    category: 'metric',
    widgetType: 'progress_bar',
    icon: 'BarChart3',
    dataRequirements: { metrics: ['value', 'target'] },
    defaultConfig: {
      title: 'Progress',
      showValue: true,
      showTarget: true,
      color: 'cyan',
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showValue', label: 'Show Value', type: 'boolean', defaultValue: true },
      { key: 'showTarget', label: 'Show Target', type: 'boolean', defaultValue: true },
      { key: 'color', label: 'Bar Color', type: 'color' },
    ],
    defaultSize: { w: 3, h: 1 },
  },
];

// ============================================
// CHART WIDGETS
// ============================================

const chartWidgets: WidgetDefinition[] = [
  {
    key: 'line_chart',
    name: 'Line Chart',
    description: 'Trend visualization over time',
    category: 'chart',
    widgetType: 'line_chart',
    icon: 'LineChart',
    dataRequirements: { metrics: ['value'], dimensions: ['date'], minDataPoints: 2 },
    defaultConfig: {
      title: 'Trend',
      xAxisKey: 'date',
      yAxisKeys: ['value'],
      showGrid: true,
      showLegend: false,
      smooth: true,
      showDots: false,
      colors: ['#0EA5E9', '#FDBA74', '#10b981'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showGrid', label: 'Show Grid', type: 'boolean', defaultValue: true },
      { key: 'showLegend', label: 'Show Legend', type: 'boolean' },
      { key: 'smooth', label: 'Smooth Lines', type: 'boolean', defaultValue: true },
      { key: 'showDots', label: 'Show Data Points', type: 'boolean' },
    ],
    defaultSize: { w: 4, h: 2 },
    minSize: { w: 2, h: 2 },
  },
  {
    key: 'bar_chart',
    name: 'Bar Chart',
    description: 'Compare values across categories',
    category: 'chart',
    widgetType: 'bar_chart',
    icon: 'BarChart',
    dataRequirements: { metrics: ['value'], dimensions: ['category'] },
    defaultConfig: {
      title: 'Comparison',
      xAxisKey: 'category',
      yAxisKeys: ['value'],
      horizontal: false,
      stacked: false,
      showGrid: true,
      showLegend: false,
      colors: ['#0EA5E9', '#FDBA74', '#10b981'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'horizontal', label: 'Horizontal', type: 'boolean' },
      { key: 'stacked', label: 'Stacked', type: 'boolean' },
      { key: 'showGrid', label: 'Show Grid', type: 'boolean', defaultValue: true },
      { key: 'showLegend', label: 'Show Legend', type: 'boolean' },
    ],
    defaultSize: { w: 4, h: 2 },
    minSize: { w: 2, h: 2 },
  },
  {
    key: 'pie_chart',
    name: 'Pie Chart',
    description: 'Show proportions of a whole',
    category: 'chart',
    widgetType: 'pie_chart',
    icon: 'PieChart',
    dataRequirements: { metrics: ['value'], dimensions: ['category'], minDataPoints: 2, maxDataPoints: 10 },
    defaultConfig: {
      title: 'Distribution',
      showLabels: true,
      showLegend: true,
      showPercentages: true,
      colors: ['#0EA5E9', '#FDBA74', '#10b981', '#f59e0b', '#ef4444'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showLabels', label: 'Show Labels', type: 'boolean', defaultValue: true },
      { key: 'showLegend', label: 'Show Legend', type: 'boolean', defaultValue: true },
      { key: 'showPercentages', label: 'Show Percentages', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 3, h: 2 },
    minSize: { w: 2, h: 2 },
  },
  {
    key: 'donut_chart',
    name: 'Donut Chart',
    description: 'Pie chart with center cutout',
    category: 'chart',
    widgetType: 'donut_chart',
    icon: 'Circle',
    dataRequirements: { metrics: ['value'], dimensions: ['category'], minDataPoints: 2, maxDataPoints: 10 },
    defaultConfig: {
      title: 'Distribution',
      showLabels: false,
      showLegend: true,
      showTotal: true,
      innerRadius: 60,
      colors: ['#0EA5E9', '#FDBA74', '#10b981', '#f59e0b', '#ef4444'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showLegend', label: 'Show Legend', type: 'boolean', defaultValue: true },
      { key: 'showTotal', label: 'Show Total in Center', type: 'boolean', defaultValue: true },
      { key: 'innerRadius', label: 'Inner Radius %', type: 'number', defaultValue: 60 },
    ],
    defaultSize: { w: 3, h: 2 },
    minSize: { w: 2, h: 2 },
  },
  {
    key: 'area_chart',
    name: 'Area Chart',
    description: 'Filled line chart for volume visualization',
    category: 'chart',
    widgetType: 'area_chart',
    icon: 'AreaChart',
    dataRequirements: { metrics: ['value'], dimensions: ['date'], minDataPoints: 2 },
    defaultConfig: {
      title: 'Volume',
      xAxisKey: 'date',
      yAxisKeys: ['value'],
      stacked: false,
      gradient: true,
      showGrid: true,
      colors: ['#0EA5E9', '#FDBA74'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'stacked', label: 'Stacked', type: 'boolean' },
      { key: 'gradient', label: 'Gradient Fill', type: 'boolean', defaultValue: true },
      { key: 'showGrid', label: 'Show Grid', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 4, h: 2 },
    minSize: { w: 2, h: 2 },
  },
  {
    key: 'radar_chart',
    name: 'Radar Chart',
    description: 'Multi-dimensional comparison',
    category: 'chart',
    widgetType: 'radar_chart',
    icon: 'Radar',
    dataRequirements: { metrics: ['value'], dimensions: ['category'], minDataPoints: 3 },
    defaultConfig: {
      title: 'Performance',
      showGrid: true,
      fillArea: true,
      colors: ['#0EA5E9', '#FDBA74'],
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showGrid', label: 'Show Grid', type: 'boolean', defaultValue: true },
      { key: 'fillArea', label: 'Fill Area', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 3, h: 3 },
    minSize: { w: 2, h: 2 },
  },
];

// ============================================
// TABLE WIDGETS
// ============================================

const tableWidgets: WidgetDefinition[] = [
  {
    key: 'data_table',
    name: 'Data Table',
    description: 'Sortable, filterable data grid',
    category: 'table',
    widgetType: 'data_table',
    icon: 'Table',
    dataRequirements: {},
    defaultConfig: {
      title: 'Data',
      columns: [],
      pageSize: 10,
      sortable: true,
      filterable: true,
      showRowNumbers: false,
      alternateRows: true,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'pageSize', label: 'Rows per Page', type: 'number', defaultValue: 10 },
      { key: 'sortable', label: 'Sortable', type: 'boolean', defaultValue: true },
      { key: 'filterable', label: 'Filterable', type: 'boolean', defaultValue: true },
      { key: 'showRowNumbers', label: 'Show Row Numbers', type: 'boolean' },
      { key: 'alternateRows', label: 'Alternate Row Colors', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 6, h: 3 },
    minSize: { w: 3, h: 2 },
  },
  {
    key: 'summary_table',
    name: 'Summary Table',
    description: 'Compact summary with key metrics',
    category: 'table',
    widgetType: 'summary_table',
    icon: 'LayoutList',
    dataRequirements: {},
    defaultConfig: {
      title: 'Summary',
      columns: [],
      showTotals: true,
      highlightMax: true,
      compact: true,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'showTotals', label: 'Show Totals Row', type: 'boolean', defaultValue: true },
      { key: 'highlightMax', label: 'Highlight Max Value', type: 'boolean', defaultValue: true },
      { key: 'compact', label: 'Compact Mode', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 4, h: 2 },
    minSize: { w: 2, h: 1 },
  },
];

// ============================================
// TEXT/DISPLAY WIDGETS
// ============================================

const textWidgets: WidgetDefinition[] = [
  {
    key: 'text_block',
    name: 'Text Block',
    description: 'Rich text content block',
    category: 'text',
    widgetType: 'text_block',
    icon: 'Type',
    dataRequirements: {},
    defaultConfig: {
      content: 'Enter your text here...',
      align: 'left',
      fontSize: 'base',
    },
    configSchema: [
      { key: 'content', label: 'Content', type: 'string' },
      { key: 'align', label: 'Alignment', type: 'select', options: [
        { value: 'left', label: 'Left' },
        { value: 'center', label: 'Center' },
        { value: 'right', label: 'Right' },
      ]},
      { key: 'fontSize', label: 'Font Size', type: 'select', options: [
        { value: 'sm', label: 'Small' },
        { value: 'base', label: 'Normal' },
        { value: 'lg', label: 'Large' },
        { value: 'xl', label: 'Extra Large' },
      ]},
    ],
    defaultSize: { w: 4, h: 1 },
  },
  {
    key: 'header',
    name: 'Section Header',
    description: 'Section title with optional description',
    category: 'text',
    widgetType: 'header',
    icon: 'Heading',
    dataRequirements: {},
    defaultConfig: {
      title: 'Section Title',
      subtitle: '',
      showDivider: true,
    },
    configSchema: [
      { key: 'title', label: 'Title', type: 'string', required: true },
      { key: 'subtitle', label: 'Subtitle', type: 'string' },
      { key: 'showDivider', label: 'Show Divider', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 6, h: 1 },
  },
];

// ============================================
// FILTER WIDGETS
// ============================================

const filterWidgets: WidgetDefinition[] = [
  {
    key: 'date_filter',
    name: 'Date Range Filter',
    description: 'Filter data by date range',
    category: 'filter',
    widgetType: 'date_filter',
    icon: 'Calendar',
    dataRequirements: {},
    defaultConfig: {
      label: 'Date Range',
      presets: ['today', 'yesterday', 'last_7_days', 'last_30_days', 'this_month', 'last_month', 'this_quarter', 'this_year'],
      defaultPreset: 'last_30_days',
      allowCustom: true,
    },
    configSchema: [
      { key: 'label', label: 'Label', type: 'string' },
      { key: 'defaultPreset', label: 'Default Preset', type: 'select', options: [
        { value: 'today', label: 'Today' },
        { value: 'last_7_days', label: 'Last 7 Days' },
        { value: 'last_30_days', label: 'Last 30 Days' },
        { value: 'this_month', label: 'This Month' },
        { value: 'this_quarter', label: 'This Quarter' },
      ]},
      { key: 'allowCustom', label: 'Allow Custom Range', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 2, h: 1 },
  },
  {
    key: 'dropdown_filter',
    name: 'Dropdown Filter',
    description: 'Select from predefined options',
    category: 'filter',
    widgetType: 'dropdown_filter',
    icon: 'ChevronDown',
    dataRequirements: {},
    defaultConfig: {
      label: 'Filter',
      options: [],
      multiple: false,
      searchable: true,
    },
    configSchema: [
      { key: 'label', label: 'Label', type: 'string' },
      { key: 'multiple', label: 'Allow Multiple', type: 'boolean' },
      { key: 'searchable', label: 'Searchable', type: 'boolean', defaultValue: true },
    ],
    defaultSize: { w: 2, h: 1 },
  },
];

// ============================================
// EXPORT ALL WIDGETS
// ============================================

export const ALL_WIDGET_DEFINITIONS: WidgetDefinition[] = [
  ...metricWidgets,
  ...chartWidgets,
  ...tableWidgets,
  ...textWidgets,
  ...filterWidgets,
];

export const WIDGETS_BY_CATEGORY: Record<WidgetCategory, WidgetDefinition[]> = {
  metric: metricWidgets,
  chart: chartWidgets,
  table: tableWidgets,
  text: textWidgets,
  filter: filterWidgets,
  custom: [],
};

export const CATEGORY_METADATA: Record<WidgetCategory, { name: string; description: string; icon: string }> = {
  metric: { name: 'Metrics', description: 'KPIs and single value displays', icon: 'Hash' },
  chart: { name: 'Charts', description: 'Data visualizations', icon: 'BarChart' },
  table: { name: 'Tables', description: 'Tabular data displays', icon: 'Table' },
  text: { name: 'Text', description: 'Headers and text blocks', icon: 'Type' },
  filter: { name: 'Filters', description: 'Interactive filters', icon: 'Filter' },
  custom: { name: 'Custom', description: 'Custom widgets', icon: 'Puzzle' },
};

// Initialize widget library in database
export async function initializeWidgetLibrary(prisma: PrismaClientType): Promise<void> {
  for (const widget of ALL_WIDGET_DEFINITIONS) {
    await prisma.reportWidget.upsert({
      where: { key: widget.key },
      update: {
        name: widget.name,
        description: widget.description,
        category: widget.category,
        widgetType: widget.widgetType,
        icon: widget.icon,
        dataRequirements: JSON.parse(JSON.stringify(widget.dataRequirements)),
        defaultConfig: JSON.parse(JSON.stringify(widget.defaultConfig)),
        configSchema: JSON.parse(JSON.stringify(widget.configSchema)),
        isActive: true,
        isSystem: true,
      },
      create: {
        key: widget.key,
        name: widget.name,
        description: widget.description,
        category: widget.category,
        widgetType: widget.widgetType,
        icon: widget.icon,
        dataRequirements: JSON.parse(JSON.stringify(widget.dataRequirements)),
        defaultConfig: JSON.parse(JSON.stringify(widget.defaultConfig)),
        configSchema: JSON.parse(JSON.stringify(widget.configSchema)),
        isActive: true,
        isSystem: true,
      },
    });
  }
}

import type { PrismaClient } from '@prisma/client';
type PrismaClientType = PrismaClient;
