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

import {
  DefaultQuality,
  getAutoRotate,
  getDefaultQuality,
  getGridColumns,
  setAutoRotate as persistAutoRotate,
  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;
  autoRotate: boolean;
  setAutoRotate: (on: boolean) => 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');
  const [autoRotate, setRotate] = useState(true);

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

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

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

  const setAutoRotate = (on: boolean) => {
    setRotate(on);
    persistAutoRotate(on).catch(() => {});
  };

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

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