import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DEFAULT_API_BASE_URL, API_URL_KEY } from '@/services/auth';

export type SortBy = 'date' | 'priority' | 'alpha' | 'created';

export const SORT_OPTIONS: { value: SortBy; label: string }[] = [
  { value: 'date', label: 'Date' },
  { value: 'priority', label: 'Priority' },
  { value: 'alpha', label: 'Alphabetically' },
  { value: 'created', label: 'Creation Date' },
];

export type ReminderPreference = 'none' | 'atTime' | '5m' | '15m' | '30m' | '1h' | '1d';

export const REMINDER_OPTIONS: { value: ReminderPreference; label: string }[] = [
  { value: 'none', label: 'No reminder' },
  { value: 'atTime', label: 'At due time' },
  { value: '5m', label: '5 minutes before' },
  { value: '15m', label: '15 minutes before' },
  { value: '30m', label: '30 minutes before' },
  { value: '1h', label: '1 hour before' },
  { value: '1d', label: '1 day before' },
];

export interface ThemeColors {
  background: string;
  card: string;
  cardAlt: string;
  border: string;
  borderStrong: string;
  text: string;
  textSecondary: string;
  textFaint: string;
  textMuted: string;
  accent: string;
  accentSoft: string;
  accentBorder: string;
  inputBg: string;
  overlay: string;
  sheetBg: string;
  tabBarBg: string;
}

export const colors: ThemeColors = {
  background: '#121212',
  card: '#1E1E1E',
  cardAlt: '#262626',
  border: '#2A2A2A',
  borderStrong: '#3A3A3A',
  text: '#F5F5F5',
  textSecondary: '#E0E0E0',
  textFaint: '#BDBDBD',
  textMuted: '#8E8E8E',
  accent: '#EF5350',
  accentSoft: '#2A1D1D',
  accentBorder: '#4A2B2B',
  inputBg: '#1A1A1A',
  overlay: 'rgba(0,0,0,0.6)',
  sheetBg: '#242424',
  tabBarBg: '#1A1A1A',
};

interface SettingsContextType {
  notifications: boolean;
  setNotifications: (value: boolean) => void;
  defaultCategoryId: string;
  setDefaultCategoryId: (value: string) => void;
  sortBy: SortBy;
  setSortBy: (value: SortBy) => void;
  reminderPreference: ReminderPreference;
  setReminderPreference: (value: ReminderPreference) => void;
  apiUrl: string;
  setApiUrl: (value: string) => void;
  theme: ThemeColors;
}

const STORAGE_KEYS = {
  notifications: 'settings:notifications',
  defaultCategoryId: 'settings:defaultCategoryId',
  sortBy: 'settings:sortBy',
  reminderPreference: 'settings:reminderPreference',
};

const SettingsContext = createContext<SettingsContextType | null>(null);

function useStoredSetting<T>(key: string, initialValue: T): [T, (value: T) => void, boolean] {
  const [value, setValue] = useState<T>(initialValue);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    AsyncStorage.getItem(key)
      .then((stored) => {
        if (stored !== null) {
          setValue(JSON.parse(stored) as T);
        }
      })
      .catch(() => {})
      .finally(() => setLoaded(true));
  }, [key]);

  const update = (next: T) => {
    setValue(next);
    AsyncStorage.setItem(key, JSON.stringify(next)).catch(() => {});
  };

  return [value, update, loaded];
}

export function SettingsProvider({ children }: { children: ReactNode }) {
  const [notifications, setNotifications] = useStoredSetting<boolean>(STORAGE_KEYS.notifications, true);
  const [defaultCategoryId, setDefaultCategoryId] = useStoredSetting<string>(STORAGE_KEYS.defaultCategoryId, '');
  const [sortBy, setSortBy] = useStoredSetting<SortBy>(STORAGE_KEYS.sortBy, 'date');
  const [reminderPreference, setReminderPreference] = useStoredSetting<ReminderPreference>(
    STORAGE_KEYS.reminderPreference,
    '15m',
  );
  const [apiUrl, setApiUrl] = useStoredSetting<string>(API_URL_KEY, DEFAULT_API_BASE_URL);

  const theme = colors;

  return (
    <SettingsContext.Provider
      value={{
        notifications,
        setNotifications,
        defaultCategoryId,
        setDefaultCategoryId,
        sortBy,
        setSortBy,
        reminderPreference,
        setReminderPreference,
        apiUrl,
        setApiUrl,
        theme,
      }}
    >
      {children}
    </SettingsContext.Provider>
  );
}

export function useSettings() {
  const context = useContext(SettingsContext);
  if (!context) {
    throw new Error('useSettings must be used within a SettingsProvider');
  }
  return context;
}
