import type { DashboardConfig, TabConfig, LayoutPreset } from '@/types';

const STORAGE_KEY = 'gold-trading-dashboard-config';

export const DEFAULT_TAB_CONFIGS: TabConfig[] = [
  {
    id: 'chart',
    label: 'Price Chart',
    visible: true,
    order: 0,
    size: 'large',
    position: 'left',
    pinned: true,
    customization: {
      autoRefresh: true,
      refreshRate: 60,
    },
  },
  {
    id: 'trade-controls',
    label: 'Trade Controls',
    visible: true,
    order: 1,
    size: 'medium',
    position: 'center',
    pinned: true,
  },
  {
    id: 'portfolio',
    label: 'Portfolio',
    visible: true,
    order: 2,
    size: 'medium',
    position: 'center',
  },
  {
    id: 'risk-management',
    label: 'Risk Management',
    visible: true,
    order: 3,
    size: 'medium',
    position: 'center',
  },
  {
    id: 'ai-analysis',
    label: 'AI Analysis',
    visible: true,
    order: 4,
    size: 'large',
    position: 'left',
  },
  {
    id: 'news',
    label: 'News Feed',
    visible: true,
    order: 5,
    size: 'medium',
    position: 'right',
    customization: {
      autoRefresh: true,
      refreshRate: 300,
      filters: { sentiment: 'ALL' },
    },
  },
  {
    id: 'alerts',
    label: 'Alerts',
    visible: true,
    order: 6,
    size: 'medium',
    position: 'right',
  },
  {
    id: 'analytics',
    label: 'Advanced Analytics',
    visible: true,
    order: 7,
    size: 'full',
    position: 'bottom',
  },
  // New Daily Trading Tools
  {
    id: 'daily-checklist',
    label: 'Daily Checklist',
    visible: false,
    order: 8,
    size: 'medium',
    position: 'left',
  },
  {
    id: 'daily-plan',
    label: 'Trading Plan',
    visible: false,
    order: 9,
    size: 'medium',
    position: 'center',
  },
  {
    id: 'trading-journal',
    label: 'Trading Journal',
    visible: false,
    order: 10,
    size: 'large',
    position: 'right',
  },
  {
    id: 'market-summary',
    label: 'Market Brief',
    visible: false,
    order: 11,
    size: 'medium',
    position: 'left',
  },
];

export const DEFAULT_PRESETS: LayoutPreset[] = [
  {
    id: 'trading-focus',
    name: 'Trading Focus',
    description: 'Optimized for active trading with chart and controls prominent',
    mode: 'grid',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[0], size: 'full', order: 0 }, // chart
      { ...DEFAULT_TAB_CONFIGS[1], size: 'medium', order: 1, visible: true }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[2], size: 'medium', order: 2, visible: true }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[3], size: 'medium', order: 3, visible: true }, // risk
      { ...DEFAULT_TAB_CONFIGS[4], size: 'medium', order: 4, visible: false }, // ai
      { ...DEFAULT_TAB_CONFIGS[5], size: 'small', order: 5, visible: true }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'small', order: 6, visible: true }, // alerts
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 7, visible: false }, // analytics
    ],
  },
  {
    id: 'analysis-focus',
    name: 'Analysis Focus',
    description: 'Full-screen analytics and AI insights',
    mode: 'tabs',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[0], size: 'full', order: 0, visible: true }, // chart
      { ...DEFAULT_TAB_CONFIGS[4], size: 'full', order: 1, visible: true }, // ai
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 2, visible: true }, // analytics
      { ...DEFAULT_TAB_CONFIGS[3], size: 'full', order: 3, visible: true }, // risk
      { ...DEFAULT_TAB_CONFIGS[2], size: 'full', order: 4, visible: true }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[5], size: 'full', order: 5, visible: true }, // news
      { ...DEFAULT_TAB_CONFIGS[1], size: 'full', order: 6, visible: false }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[6], size: 'full', order: 7, visible: false }, // alerts
    ],
  },
  {
    id: 'news-focus',
    name: 'News Focus',
    description: 'News and market updates at the forefront',
    mode: 'split',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[0], size: 'large', order: 0, position: 'left' }, // chart
      { ...DEFAULT_TAB_CONFIGS[5], size: 'large', order: 1, position: 'right' }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'medium', order: 2, position: 'right' }, // alerts
      { ...DEFAULT_TAB_CONFIGS[4], size: 'medium', order: 3, position: 'left' }, // ai
      { ...DEFAULT_TAB_CONFIGS[1], size: 'small', order: 4, position: 'left', visible: false },
      { ...DEFAULT_TAB_CONFIGS[2], size: 'small', order: 5, position: 'left', visible: false },
      { ...DEFAULT_TAB_CONFIGS[3], size: 'small', order: 6, position: 'left', visible: false },
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 7, visible: false }, // analytics
    ],
  },
  {
    id: 'balanced',
    name: 'Balanced View',
    description: 'Equal emphasis on all components',
    mode: 'grid',
    tabs: DEFAULT_TAB_CONFIGS.map((tab, index) => ({ ...tab, order: index, visible: true })),
  },
  // Daily Trading Workflow Presets
  {
    id: 'morning-setup',
    name: '🌅 Morning Setup',
    description: 'Pre-market routine: checklist, plan, and market brief',
    mode: 'grid',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[11], size: 'large', order: 0, visible: true }, // market summary
      { ...DEFAULT_TAB_CONFIGS[8], size: 'medium', order: 1, visible: true }, // checklist
      { ...DEFAULT_TAB_CONFIGS[9], size: 'medium', order: 2, visible: true }, // trading plan
      { ...DEFAULT_TAB_CONFIGS[0], size: 'large', order: 3, visible: true }, // chart
      { ...DEFAULT_TAB_CONFIGS[5], size: 'medium', order: 4, visible: true }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'medium', order: 5, visible: true }, // alerts
      { ...DEFAULT_TAB_CONFIGS[4], size: 'medium', order: 6, visible: true }, // ai
      { ...DEFAULT_TAB_CONFIGS[1], size: 'small', order: 7, visible: false }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[2], size: 'small', order: 8, visible: false }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[3], size: 'small', order: 9, visible: false }, // risk
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 10, visible: false }, // analytics
      { ...DEFAULT_TAB_CONFIGS[10], size: 'large', order: 11, visible: false }, // journal
    ],
  },
  {
    id: 'active-trading',
    name: '📈 Active Trading',
    description: 'During market hours: chart, controls, and execution',
    mode: 'grid',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[0], size: 'full', order: 0, visible: true, pinned: true }, // chart
      { ...DEFAULT_TAB_CONFIGS[1], size: 'medium', order: 1, visible: true, pinned: true }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[2], size: 'medium', order: 2, visible: true }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[3], size: 'medium', order: 3, visible: true }, // risk
      { ...DEFAULT_TAB_CONFIGS[9], size: 'medium', order: 4, visible: true }, // trading plan
      { ...DEFAULT_TAB_CONFIGS[8], size: 'small', order: 5, visible: true }, // checklist
      { ...DEFAULT_TAB_CONFIGS[5], size: 'medium', order: 6, visible: true }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'medium', order: 7, visible: true }, // alerts
      { ...DEFAULT_TAB_CONFIGS[10], size: 'medium', order: 8, visible: false }, // journal (quick access)
      { ...DEFAULT_TAB_CONFIGS[4], size: 'medium', order: 9, visible: false }, // ai
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 10, visible: false }, // analytics
      { ...DEFAULT_TAB_CONFIGS[11], size: 'medium', order: 11, visible: false }, // market summary
    ],
  },
  {
    id: 'end-of-day-review',
    name: '🌙 End-of-Day Review',
    description: 'Post-market analysis: journal, analytics, and planning for tomorrow',
    mode: 'tabs',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[10], size: 'full', order: 0, visible: true }, // journal
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 1, visible: true }, // analytics
      { ...DEFAULT_TAB_CONFIGS[8], size: 'full', order: 2, visible: true }, // checklist
      { ...DEFAULT_TAB_CONFIGS[9], size: 'full', order: 3, visible: true }, // trading plan
      { ...DEFAULT_TAB_CONFIGS[2], size: 'full', order: 4, visible: true }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[0], size: 'full', order: 5, visible: true }, // chart
      { ...DEFAULT_TAB_CONFIGS[11], size: 'full', order: 6, visible: false }, // market summary
      { ...DEFAULT_TAB_CONFIGS[1], size: 'full', order: 7, visible: false }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[3], size: 'full', order: 8, visible: false }, // risk
      { ...DEFAULT_TAB_CONFIGS[4], size: 'full', order: 9, visible: false }, // ai
      { ...DEFAULT_TAB_CONFIGS[5], size: 'full', order: 10, visible: false }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'full', order: 11, visible: false }, // alerts
    ],
  },
  {
    id: 'daily-trader',
    name: '⚡ Complete Daily Trader',
    description: 'All daily trading tools visible for comprehensive workflow',
    mode: 'grid',
    tabs: [
      { ...DEFAULT_TAB_CONFIGS[0], size: 'large', order: 0, visible: true, position: 'left' }, // chart
      { ...DEFAULT_TAB_CONFIGS[11], size: 'medium', order: 1, visible: true, position: 'left' }, // market summary
      { ...DEFAULT_TAB_CONFIGS[1], size: 'medium', order: 2, visible: true, position: 'center' }, // trade controls
      { ...DEFAULT_TAB_CONFIGS[9], size: 'medium', order: 3, visible: true, position: 'center' }, // trading plan
      { ...DEFAULT_TAB_CONFIGS[8], size: 'medium', order: 4, visible: true, position: 'center' }, // checklist
      { ...DEFAULT_TAB_CONFIGS[2], size: 'medium', order: 5, visible: true, position: 'center' }, // portfolio
      { ...DEFAULT_TAB_CONFIGS[5], size: 'medium', order: 6, visible: true, position: 'right' }, // news
      { ...DEFAULT_TAB_CONFIGS[6], size: 'medium', order: 7, visible: true, position: 'right' }, // alerts
      { ...DEFAULT_TAB_CONFIGS[10], size: 'large', order: 8, visible: true, position: 'right' }, // journal
      { ...DEFAULT_TAB_CONFIGS[3], size: 'medium', order: 9, visible: false }, // risk
      { ...DEFAULT_TAB_CONFIGS[4], size: 'medium', order: 10, visible: false }, // ai
      { ...DEFAULT_TAB_CONFIGS[7], size: 'full', order: 11, visible: false }, // analytics
    ],
  },
];

export const DEFAULT_DASHBOARD_CONFIG: DashboardConfig = {
  mode: 'grid',
  tabs: DEFAULT_TAB_CONFIGS,
  activePreset: 'balanced',
  customPresets: [],
};

export function loadDashboardConfig(): DashboardConfig {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      const config = JSON.parse(stored);
      const storedTabs: TabConfig[] = config.tabs || [];
      const defaultTabsById = new Map(DEFAULT_TAB_CONFIGS.map((tab) => [tab.id, tab]));

      // Merge stored tab settings with defaults so required tabs always exist
      const mergedTabs = DEFAULT_TAB_CONFIGS.map((defaultTab) => {
        const storedTab = storedTabs.find((tab) => tab.id === defaultTab.id);
        return storedTab ? { ...defaultTab, ...storedTab } : defaultTab;
      });

      // Preserve any custom tabs user may have added that aren't in defaults
      const additionalTabs = storedTabs.filter((tab) => !defaultTabsById.has(tab.id));

      return {
        ...DEFAULT_DASHBOARD_CONFIG,
        ...config,
        tabs: [...mergedTabs, ...additionalTabs],
      };
    }
  } catch (error) {
    console.error('Error loading dashboard config:', error);
  }
  return DEFAULT_DASHBOARD_CONFIG;
}

export function saveDashboardConfig(config: DashboardConfig): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(config));
  } catch (error) {
    console.error('Error saving dashboard config:', error);
  }
}

export function getPresetById(presetId: string): LayoutPreset | undefined {
  return DEFAULT_PRESETS.find((p) => p.id === presetId);
}

export function applyPreset(config: DashboardConfig, presetId: string): DashboardConfig {
  const preset = getPresetById(presetId);
  if (!preset) {
    // Check custom presets
    const customPreset = config.customPresets.find((p) => p.id === presetId);
    if (customPreset) {
      return {
        ...config,
        mode: customPreset.mode,
        tabs: customPreset.tabs,
        activePreset: presetId,
      };
    }
    return config;
  }

  return {
    ...config,
    mode: preset.mode,
    tabs: preset.tabs,
    activePreset: presetId,
  };
}

export function saveCustomPreset(
  config: DashboardConfig,
  name: string,
  description: string
): DashboardConfig {
  const newPreset: LayoutPreset = {
    id: `custom-${Date.now()}`,
    name,
    description,
    mode: config.mode,
    tabs: [...config.tabs],
  };

  return {
    ...config,
    customPresets: [...config.customPresets, newPreset],
  };
}

export function resetToDefault(): DashboardConfig {
  return { ...DEFAULT_DASHBOARD_CONFIG };
}
