import { useCallback } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';

const QUERY_KEY = ['USER_SETTINGS'];

const mergeWithDefaults = (saved: Partial<UserSettings>): UserSettings => ({
  chat: { ...DEFAULT_SETTINGS.chat, ...saved.chat },
  ai: {
    enabledModels: saved.ai?.enabledModels?.length ? saved.ai.enabledModels : DEFAULT_SETTINGS.ai.enabledModels,
    enabledProviders: saved.ai?.enabledProviders ?? DEFAULT_SETTINGS.ai.enabledProviders,
    disabledProviders: saved.ai?.disabledProviders ?? DEFAULT_SETTINGS.ai.disabledProviders,
  },
  tasks: { ...DEFAULT_SETTINGS.tasks, ...saved.tasks },
  appearance: { ...DEFAULT_SETTINGS.appearance, ...saved.appearance },
  languages: { ...DEFAULT_SETTINGS.languages, ...saved.languages },
  tts: { ...DEFAULT_SETTINGS.tts, ...saved.tts },
});

export const useSettings = () => {
  const client = useClient();
  const { isAuthenticated } = useAuth();
  const queryClient = useQueryClient();

  const { data: settings = DEFAULT_SETTINGS } = useQuery<UserSettings>({
    queryKey: QUERY_KEY,
    enabled: isAuthenticated,
    queryFn: async () => {
      const saved = await client.get<Partial<UserSettings>>('/user/settings');
      return mergeWithDefaults(saved);
    },
    staleTime: Infinity,
  });

  const saveSettings = useCallback(
    async (newSettings: UserSettings) => {
      queryClient.setQueryData(QUERY_KEY, newSettings);
      await client.put<UserSettings>('/user/settings', newSettings);
    },
    [client, queryClient],
  );

  return { settings, saveSettings };
};

export type UseSettingsType = ReturnType<typeof useSettings>;

export type UserSettings = {
  chat: {
    defaultProvider: 'chat';
    defaultModel: string | null;
    defaultProjectModel: string | null;
    systemPrompt: string;
    temperature: number;
    defaultPwd: string;
    hiddenModels?: string[];
  };
  ai: {
    enabledModels: string[];
    enabledProviders: string[];
    disabledProviders: string[];
  };
  tasks: {
    defaultProvider: 'chat';
    defaultModel: string | null;
  };
  appearance: {
    colorMode: 'light' | 'dark';
  };
  languages: {
    spoken: string[];
    default: string;
    translateTo: string;
  };
  tts: {
    voice: string | null;
  };
};

export type UserState = Record<string, unknown>;

export const DEFAULT_SETTINGS: UserSettings = {
  chat: {
    defaultProvider: 'chat',
    defaultModel: 'claude-code',
    defaultProjectModel: 'claude-code',
    systemPrompt: '',
    temperature: 1,
    defaultPwd: '~',
  },
  ai: {
    enabledModels: [],
    enabledProviders: [],
    disabledProviders: [],
  },
  tasks: {
    defaultProvider: 'chat',
    defaultModel: 'claude-code',
  },
  appearance: {
    colorMode: 'light',
  },
  languages: {
    spoken: ['en'],
    default: 'en',
    translateTo: 'en',
  },
  tts: {
    voice: null,
  },
};
