import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Settings } from '../types';
import { api } from '../services/api';

const fetchSettings = async (): Promise<Settings> => {
  const { data } = await api.get<Settings>('/settings');
  return data;
};

const updateSettings = async (settings: Partial<Settings>): Promise<Settings> => {
  const { data } = await api.put<Settings>('/settings', settings);
  return data;
};

const defaultSettings: Settings = {
  id: 'default',
  clubId: '',
  clubType: '',
  primaryColor: '#3182ce', // Direct access to primary color
  theme: {
    primaryColor: '#3182ce',
    secondaryColor: '#2b6cb0',
    fontFamily: 'Inter, sans-serif',
  },
  socialLinks: {},
  contactInfo: {
    address: 'Ulice a číslo, Město, PSČ',
    phone: '+420 123 456 789',
    email: 'info@vas-klub.cz',
    website: 'www.vas-klub.cz',
    workingHours: 'Pondělí - Pátek: 9:00 - 17:00',
  },
  features: {
    darkMode: false,
    notifications: true,
    analytics: false,
  },
  updatedAt: new Date().toISOString(),
  createdAt: new Date().toISOString(),
};

export const useSettings = () => {
  const queryClient = useQueryClient();

  const { data: settings = defaultSettings, isLoading } = useQuery<Settings>({
    queryKey: ['settings'],
    queryFn: fetchSettings,
    staleTime: 1000 * 60 * 5, // 5 minutes
    onError: (error) => {
      console.error('Failed to load settings:', error);
    },
  });

  const updateSettingsMutation = useMutation({
    mutationFn: updateSettings,
    onSuccess: (data) => {
      queryClient.setQueryData<Settings>(['settings'], (old) => ({
        ...defaultSettings,
        ...old,
        ...data,
      }));
    },
  });

  const updateTheme = (theme: Settings['theme']) => {
    updateSettingsMutation.mutate({
      theme: { ...settings.theme, ...theme },
    });
  };

  const updateSocialLinks = (socialLinks: Settings['socialLinks']) => {
    updateSettingsMutation.mutate({
      socialLinks: { ...settings.socialLinks, ...socialLinks },
    });
  };

  const updateFeatures = (features: Partial<Settings['features']>) => {
    updateSettingsMutation.mutate({
      features: { ...settings.features, ...features },
    });
  };

  return {
    settings,
    isLoading,
    updateTheme,
    updateSocialLinks,
    updateFeatures,
    updateSettings: updateSettingsMutation.mutateAsync,
    isUpdating: updateSettingsMutation.isLoading,
  };
};
