const express = require('express');
const router = express.Router();
const { getSettings, updateSetting, getDb } = require('../db');
const { THEME_PRESETS, THEME_CSS_KEYS, THEME_MAIN_COLORS, THEME_COLOR_LABELS } = require('../themes');

const ALL_ICONS = [
  { key: 'layout-dashboard', label: 'Dashboard' },
  { key: 'users', label: 'Cliënten' },
  { key: 'briefcase', label: 'Engagements' },
  { key: 'server', label: 'Infrastructuur' },
  { key: 'check-circle', label: 'Taken' },
  { key: 'lightbulb', label: 'Advies' },
  { key: 'clock', label: 'Activiteit' },
  { key: 'eye', label: 'Overzicht (client)' },
  { key: 'phone', label: 'Contact' },
  { key: 'file-text', label: 'Designs' },
  { key: 'edit-3', label: 'Notities' },
  { key: 'folder', label: 'Bestanden' },
  { key: 'clipboard-list', label: 'Assessments' }
];

function toHexForPicker(val, fallback) {
  if (val && /^#[0-9a-f]{6}$/i.test(val)) return val;
  return fallback || '#0a1628';
}

function getMergedThemeColors(settings) {
  const preset = THEME_PRESETS[settings.theme] || THEME_PRESETS['mek-neon-blue'];
  const custom = settings.theme_colors || {};
  const merged = {};
  THEME_CSS_KEYS.forEach(k => { merged[k] = custom[k] || preset[k] || ''; });
  return { preset, custom, merged };
}

router.get('/', (req, res) => {
  const settings = getSettings();
  const { preset, custom, merged } = getMergedThemeColors(settings);
  const useCustomColors = Object.keys(custom).length > 0 || settings.theme === 'custom';
  res.render('settings', {
    settings,
    icons: ALL_ICONS,
    themePresets: THEME_PRESETS,
    themeCssKeys: THEME_CSS_KEYS,
    themeMainColors: THEME_MAIN_COLORS,
    themeColorLabels: THEME_COLOR_LABELS,
    mergedColors: merged,
    useCustomColors,
    toHexForPicker,
    user: { username: req.session.username },
    saved: req.query.saved === '1'
  });
});

router.post('/', (req, res) => {
  const { brand_name, language, theme, default_page, auto_refresh, items_per_page, debug_mode, slack_webhook, smtp_host, smtp_user, smtp_pass, use_custom_colors, showcase_url } = req.body;

  updateSetting('brand_name', brand_name || 'Mek-Tech Consulting');
  updateSetting('showcase_url', showcase_url || 'http://192.168.1.247:3010');
  updateSetting('language', language || 'nl');
  updateSetting('default_page', default_page || '/');
  updateSetting('auto_refresh', auto_refresh || '0');
  updateSetting('items_per_page', items_per_page || '50');
  updateSetting('debug_mode', debug_mode === '1' ? '1' : '0');
  updateSetting('slack_webhook', slack_webhook || '');
  updateSetting('smtp_host', smtp_host || '');
  updateSetting('smtp_user', smtp_user || '');
  updateSetting('smtp_pass', smtp_pass || '');

  const icon_colors = {};
  ALL_ICONS.forEach(icon => {
    const val = req.body['color_' + icon.key.replace(/-/g, '_')];
    if (val) icon_colors[icon.key] = val;
  });
  updateSetting('icon_colors', icon_colors);

  const themeColors = {};
  if (use_custom_colors === '1') {
    THEME_CSS_KEYS.forEach(k => {
      const val = req.body['th_' + k];
      if (val && String(val).trim()) themeColors[k] = String(val).trim();
    });
    updateSetting('theme', 'custom');
    updateSetting('theme_colors', themeColors);
  } else {
    updateSetting('theme', theme || 'mek-neon-blue');
    updateSetting('theme_colors', {});
  }

  res.redirect('/settings?saved=1');
});

router.post('/reset', (req, res) => {
  const d = getDb();
  d.prepare('DELETE FROM app_settings').run();
  res.redirect('/settings');
});

module.exports = { router, THEME_PRESETS, THEME_CSS_KEYS, ALL_ICONS };
