import { createContext, useContext, useEffect, useState } from "react";

type AccessibilitySettings = {
  highContrast: boolean;
  reducedMotion: boolean;
  largeText: boolean;
  screenReaderMode: boolean;
  keyboardNavigation: boolean;
};

type AccessibilityProviderProps = {
  children: React.ReactNode;
  storageKey?: string;
};

type AccessibilityProviderState = {
  settings: AccessibilitySettings;
  updateSetting: (key: keyof AccessibilitySettings, value: boolean) => void;
  resetSettings: () => void;
};

const defaultSettings: AccessibilitySettings = {
  highContrast: false,
  reducedMotion: false,
  largeText: false,
  screenReaderMode: false,
  keyboardNavigation: true,
};

const AccessibilityContext = createContext<AccessibilityProviderState | undefined>(undefined);

export function AccessibilityProvider({
  children,
  storageKey = "rugby-app-accessibility",
  ...props
}: AccessibilityProviderProps) {
  const [settings, setSettings] = useState<AccessibilitySettings>(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        return { ...defaultSettings, ...JSON.parse(stored) };
      }
    } catch (error) {
      console.warn("Failed to load accessibility settings:", error);
    }
    return defaultSettings;
  });

  useEffect(() => {
    const root = document.documentElement;
    
    // Apply high contrast mode
    if (settings.highContrast) {
      root.classList.add("high-contrast");
    } else {
      root.classList.remove("high-contrast");
    }

    // Apply reduced motion
    if (settings.reducedMotion) {
      root.classList.add("reduce-motion");
    } else {
      root.classList.remove("reduce-motion");
    }

    // Apply large text
    if (settings.largeText) {
      root.classList.add("large-text");
    } else {
      root.classList.remove("large-text");
    }

    // Apply screen reader mode
    if (settings.screenReaderMode) {
      root.classList.add("screen-reader");
    } else {
      root.classList.remove("screen-reader");
    }

    // Apply keyboard navigation enhancements
    if (settings.keyboardNavigation) {
      root.classList.add("keyboard-nav");
    } else {
      root.classList.remove("keyboard-nav");
    }

    // Save to localStorage
    localStorage.setItem(storageKey, JSON.stringify(settings));
  }, [settings, storageKey]);

  // Listen for system preferences
  useEffect(() => {
    const handleMotionPreference = (e: MediaQueryListEvent) => {
      if (e.matches && !settings.reducedMotion) {
        updateSetting("reducedMotion", true);
      }
    };

    const motionMediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
    motionMediaQuery.addEventListener("change", handleMotionPreference);

    // Check initial state
    if (motionMediaQuery.matches && !settings.reducedMotion) {
      updateSetting("reducedMotion", true);
    }

    return () => {
      motionMediaQuery.removeEventListener("change", handleMotionPreference);
    };
  }, [settings.reducedMotion]);

  const updateSetting = (key: keyof AccessibilitySettings, value: boolean) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const resetSettings = () => {
    setSettings(defaultSettings);
  };

  const value = {
    settings,
    updateSetting,
    resetSettings,
  };

  return (
    <AccessibilityContext.Provider {...props} value={value}>
      {children}
    </AccessibilityContext.Provider>
  );
}

export const useAccessibility = () => {
  const context = useContext(AccessibilityContext);

  if (context === undefined) {
    throw new Error("useAccessibility must be used within an AccessibilityProvider");
  }

  return context;
};