import React, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type { ADHDSettings } from '@shared/schema';

const defaultADHDSettings: ADHDSettings = {
  reducedAnimations: false,
  largerTargets: true,
  breakReminderInterval: 45,
  singleTaskModeDefault: false,
  positiveMessagingLevel: 'normal',
  hyperfocusProtection: true,
  hyperfocusMaxMinutes: 90,
  visualTimerEnabled: true,
  quickWinThreshold: 10,
  energyCheckInsEnabled: true,
};

interface ADHDModeContextType {
  isEnabled: boolean;
  settings: ADHDSettings;
  toggle: () => void;
  updateSettings: (settings: Partial<ADHDSettings>) => void;
  isLoading: boolean;
}

const ADHDModeContext = createContext<ADHDModeContextType | undefined>(undefined);

export function ADHDModeProvider({ children }: { children: ReactNode }) {
  const queryClient = useQueryClient();

  // Fetch user data to get ADHD settings
  const { data: user, isLoading } = useQuery<{
    adhdMode: boolean;
    adhdSettings: ADHDSettings;
  }>({
    queryKey: ['/api/user'],
  });

  const [localEnabled, setLocalEnabled] = useState(false);
  const [localSettings, setLocalSettings] = useState<ADHDSettings>(defaultADHDSettings);

  // Sync with server data
  useEffect(() => {
    if (user) {
      setLocalEnabled(user.adhdMode ?? false);
      setLocalSettings(user.adhdSettings ?? defaultADHDSettings);
    }
  }, [user]);

  // Apply ADHD mode class to document
  useEffect(() => {
    const root = document.documentElement;
    if (localEnabled) {
      root.classList.add('adhd-mode');
      if (localSettings.reducedAnimations) {
        root.classList.add('reduced-motion');
      } else {
        root.classList.remove('reduced-motion');
      }
      if (localSettings.largerTargets) {
        root.classList.add('larger-targets');
      } else {
        root.classList.remove('larger-targets');
      }
    } else {
      root.classList.remove('adhd-mode', 'reduced-motion', 'larger-targets');
    }
  }, [localEnabled, localSettings]);

  // Mutation to update ADHD settings
  const updateMutation = useMutation({
    mutationFn: async (data: { adhdMode: boolean; adhdSettings: ADHDSettings }) => {
      const res = await fetch('/api/user/adhd-settings', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error('Failed to update ADHD settings');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/user'] });
    },
  });

  const toggle = useCallback(() => {
    const newEnabled = !localEnabled;
    setLocalEnabled(newEnabled);
    updateMutation.mutate({ adhdMode: newEnabled, adhdSettings: localSettings });
  }, [localEnabled, localSettings, updateMutation]);

  const updateSettings = useCallback((newSettings: Partial<ADHDSettings>) => {
    const merged = { ...localSettings, ...newSettings };
    setLocalSettings(merged);
    updateMutation.mutate({ adhdMode: localEnabled, adhdSettings: merged });
  }, [localEnabled, localSettings, updateMutation]);

  return (
    <ADHDModeContext.Provider
      value={{
        isEnabled: localEnabled,
        settings: localSettings,
        toggle,
        updateSettings,
        isLoading,
      }}
    >
      {children}
    </ADHDModeContext.Provider>
  );
}

export function useADHDMode() {
  const context = useContext(ADHDModeContext);
  if (context === undefined) {
    throw new Error('useADHDMode must be used within an ADHDModeProvider');
  }
  return context;
}

export { defaultADHDSettings };
