import React, { createContext, useContext, useEffect, useState } from 'react';

import {
  DefaultQuality,
  getDefaultQuality,
  getGridColumns,
  setDefaultQuality as persistDefaultQuality,
  setGridColumns as persistGridColumns,
} from './storage';

/**
 * Globalne preferencje UI. Ładowane raz przy montażu z SecureStore (async) i dalej
 * trzymane synchronicznie w state, żeby ekrany czytały wartość w renderze bez await.
 */
interface Prefs {
  gridColumns: number;
  setGridColumns: (n: number) => void;
  defaultQuality: DefaultQuality;
  setDefaultQuality: (q: DefaultQuality) => void;
}

const Ctx = createContext<Prefs | null>(null);

export function PreferencesProvider({ children }: { children: React.ReactNode }) {
  const [gridColumns, setCols] = useState(2);
  const [defaultQuality, setQuality] = useState<DefaultQuality>('auto');

  useEffect(() => {
    getGridColumns()
      .then(setCols)
      .catch(() => {});
    getDefaultQuality()
      .then(setQuality)
      .catch(() => {});
  }, []);

  const setGridColumns = (n: number) => {
    setCols(n);
    persistGridColumns(n).catch(() => {});
  };

  const setDefaultQuality = (q: DefaultQuality) => {
    setQuality(q);
    persistDefaultQuality(q).catch(() => {});
  };

  return (
    <Ctx.Provider value={{ gridColumns, setGridColumns, defaultQuality, setDefaultQuality }}>
      {children}
    </Ctx.Provider>
  );
}

export function usePreferences(): Prefs {
  const c = useContext(Ctx);
  if (!c) throw new Error('usePreferences outside PreferencesProvider');
  return c;
}
