import { createContext, useContext, useEffect, useState, useCallback, useRef } from 'react';
import { api } from '../api.js';

/**
 * UI state that persists across sessions:
 *   - sidebarCollapsed : sidebar visibility
 *   - fontScale        : 'large' (max/accessibilité) | 'medium' | 'compact'
 */

const UiCtx = createContext(null);

const KEY_SIDEBAR  = 'cl_ui_sidebar_collapsed';
const KEY_FONT     = 'cl_fontscale';
const KEY_LANGUE   = 'cl_langue';
const KEY_DEVISE   = 'cl_devise';
const KEY_DISPLAY  = 'cl_display_mode';
const KEY_CHART_INTERETS = 'cl_chart_interets';
const KEY_CHART_CAPITAL  = 'cl_chart_capital';
const KEY_CHART_CASHBACK = 'cl_chart_cashback';
const KEY_PFO_ASSUJETTI  = 'cl_pfo_assujetti';

const FONT_SIZES = ['large', 'medium', 'compact'];
const LANGUES    = ['fr', 'en'];
const DEVISES    = ['EUR', 'USD', 'GBP', 'CHF', 'CAD', 'SGD'];

const DEFAULT_CHART_INTERETS = '#2196f3'; // Blue 500
const DEFAULT_CHART_CAPITAL  = '#4caf50'; // Green 500
const DEFAULT_CHART_CASHBACK = '#ffc107'; // Amber 500

function applyFontScale(scale) {
  document.documentElement.setAttribute('data-fontsize', scale);
}

export function UiProvider({ children }) {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(
    () => localStorage.getItem(KEY_SIDEBAR) === '1'
  );

  const [fontScale, setFontScaleState] = useState(() => {
    const saved = localStorage.getItem(KEY_FONT);
    return FONT_SIZES.includes(saved) ? saved : 'large';
  });

  const [langue, setLangueState] = useState(() => {
    const saved = localStorage.getItem(KEY_LANGUE);
    return LANGUES.includes(saved) ? saved : 'fr';
  });

  const [devise, setDeviseState] = useState(() => {
    const saved = localStorage.getItem(KEY_DEVISE);
    return DEVISES.includes(saved) ? saved : 'EUR';
  });

  const [displayMode, setDisplayModeState] = useState(() => {
    const saved = localStorage.getItem(KEY_DISPLAY);
    return saved === 'brut' ? 'brut' : 'net';
  });

  const [chartInterets, setChartInteretsState] = useState(() =>
    localStorage.getItem(KEY_CHART_INTERETS) || DEFAULT_CHART_INTERETS
  );
  const [chartCapital, setChartCapitalState] = useState(() =>
    localStorage.getItem(KEY_CHART_CAPITAL) || DEFAULT_CHART_CAPITAL
  );
  const [chartCashback, setChartCashbackState] = useState(() =>
    localStorage.getItem(KEY_CHART_CASHBACK) || DEFAULT_CHART_CASHBACK
  );

  const [pfoAssujetti, setPfoAssujettiState] = useState(() =>
    localStorage.getItem(KEY_PFO_ASSUJETTI) === '1'
  );

  // ── Sync DB → localStorage au montage ──────────────────────────
  // La DB fait foi : ses valeurs écrasent le localStorage si présentes.
  useEffect(() => {
    api.get('/preferences').then(prefs => {
      if (prefs.chart_interets) {
        localStorage.setItem(KEY_CHART_INTERETS, prefs.chart_interets);
        setChartInteretsState(prefs.chart_interets);
      }
      if (prefs.chart_capital) {
        localStorage.setItem(KEY_CHART_CAPITAL, prefs.chart_capital);
        setChartCapitalState(prefs.chart_capital);
      }
      if (prefs.chart_cashback) {
        localStorage.setItem(KEY_CHART_CASHBACK, prefs.chart_cashback);
        setChartCashbackState(prefs.chart_cashback);
      }
      if (prefs.pfo_assujetti !== undefined) {
        const val = prefs.pfo_assujetti === '1';
        localStorage.setItem(KEY_PFO_ASSUJETTI, val ? '1' : '0');
        setPfoAssujettiState(val);
      }
    }).catch(() => {
      // Silencieux : token absent au premier rendu, on garde le localStorage
    });
  }, []);

  // ── Helper : persist une pref en DB (silencieux en cas d'erreur) ─
  const persistPref = useCallback((key, value) => {
    api.patch('/preferences', { [key]: value }).catch(() => {});
  }, []);

  useEffect(() => {
    localStorage.setItem(KEY_SIDEBAR, sidebarCollapsed ? '1' : '0');
  }, [sidebarCollapsed]);

  useEffect(() => {
    applyFontScale(fontScale);
    localStorage.setItem(KEY_FONT, fontScale);
  }, [fontScale]);

  // Apply on mount
  useEffect(() => { applyFontScale(fontScale); }, []);

  const toggleSidebar = useCallback(() => setSidebarCollapsed((v) => !v), []);
  const setFontScale  = useCallback((s) => {
    if (FONT_SIZES.includes(s)) setFontScaleState(s);
  }, []);
  const setLangue = useCallback((l) => {
    if (LANGUES.includes(l)) { setLangueState(l); localStorage.setItem(KEY_LANGUE, l); }
  }, []);
  const setDevise = useCallback((d) => {
    if (DEVISES.includes(d)) { setDeviseState(d); localStorage.setItem(KEY_DEVISE, d); }
  }, []);

  const setDisplayMode = useCallback((m) => {
    if (m === 'net' || m === 'brut') {
      setDisplayModeState(m);
      localStorage.setItem(KEY_DISPLAY, m);
    }
  }, []);

  const setChartInterets = useCallback((hex) => {
    setChartInteretsState(hex);
    localStorage.setItem(KEY_CHART_INTERETS, hex);
    persistPref('chart_interets', hex);
  }, [persistPref]);

  const setChartCapital = useCallback((hex) => {
    setChartCapitalState(hex);
    localStorage.setItem(KEY_CHART_CAPITAL, hex);
    persistPref('chart_capital', hex);
  }, [persistPref]);

  const setChartCashback = useCallback((hex) => {
    setChartCashbackState(hex);
    localStorage.setItem(KEY_CHART_CASHBACK, hex);
    persistPref('chart_cashback', hex);
  }, [persistPref]);

  const setPfoAssujetti = useCallback((val) => {
    setPfoAssujettiState(val);
    localStorage.setItem(KEY_PFO_ASSUJETTI, val ? '1' : '0');
    persistPref('pfo_assujetti', val ? '1' : '0');
  }, [persistPref]);

  return (
    <UiCtx.Provider value={{ sidebarCollapsed, setSidebarCollapsed, toggleSidebar, fontScale, setFontScale, langue, setLangue, devise, setDevise, displayMode, setDisplayMode, chartInterets, setChartInterets, chartCapital, setChartCapital, chartCashback, setChartCashback, pfoAssujetti, setPfoAssujetti }}>
      {children}
    </UiCtx.Provider>
  );
}

export const useUi = () => useContext(UiCtx);
