import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { getCalendarSyncSettingStatus, updateCalendarSyncSetting } from "@/lib/api/settings.api";

type SummaryModel = "gpt-4o" | "gpt-4o-mini" | "gpt-3.5-turbo";
type Language = "en" | "es" | "fr" | "de" | "ja";

interface SettingsState {
  // Transcription
  language: Language;
  speakerIdentification: boolean;
  autoGenerateSummary: boolean;

  // Notifications
  notifyOnComplete: boolean;
  notifyOnSummary: boolean;
  notifyActionItems: boolean;

  // API
  summaryModel: SummaryModel;
  openAiKeySet: boolean;

  // Calendar automation
  calendarEventBotSync: boolean;
  isCalendarEventBotSyncLoading: boolean;
  isCalendarEventBotSyncSaving: boolean;

  // Actions
  setLanguage: (lang: Language) => void;
  setSpeakerIdentification: (val: boolean) => void;
  setAutoGenerateSummary: (val: boolean) => void;
  setNotifyOnComplete: (val: boolean) => void;
  setNotifyOnSummary: (val: boolean) => void;
  setNotifyActionItems: (val: boolean) => void;
  setSummaryModel: (model: SummaryModel) => void;
  setOpenAiKeySet: (val: boolean) => void;
  setCalendarEventBotSync: (val: boolean) => void;
  fetchCalendarEventBotSync: () => Promise<void>;
  updateCalendarEventBotSync: (enabled: boolean) => Promise<void>;
}

export const useSettingsStore = create<SettingsState>()(
  devtools(
    persist(
      (set) => ({
        language: "en",
        speakerIdentification: true,
        autoGenerateSummary: true,
        notifyOnComplete: true,
        notifyOnSummary: true,
        notifyActionItems: true,
        summaryModel: "gpt-4o",
        openAiKeySet: false,
        calendarEventBotSync: false,
        isCalendarEventBotSyncLoading: false,
        isCalendarEventBotSyncSaving: false,

        setLanguage: (language) =>
          set({ language }, false, "settings/setLanguage"),

        setSpeakerIdentification: (speakerIdentification) =>
          set({ speakerIdentification }, false, "settings/setSpeakerIdentification"),

        setAutoGenerateSummary: (autoGenerateSummary) =>
          set({ autoGenerateSummary }, false, "settings/setAutoGenerateSummary"),

        setNotifyOnComplete: (notifyOnComplete) =>
          set({ notifyOnComplete }, false, "settings/setNotifyOnComplete"),

        setNotifyOnSummary: (notifyOnSummary) =>
          set({ notifyOnSummary }, false, "settings/setNotifyOnSummary"),

        setNotifyActionItems: (notifyActionItems) =>
          set({ notifyActionItems }, false, "settings/setNotifyActionItems"),

        setSummaryModel: (summaryModel) =>
          set({ summaryModel }, false, "settings/setSummaryModel"),

        setOpenAiKeySet: (openAiKeySet) =>
          set({ openAiKeySet }, false, "settings/setOpenAiKeySet"),

        setCalendarEventBotSync: (calendarEventBotSync) =>
          set({ calendarEventBotSync }, false, "settings/setCalendarEventBotSync"),

        fetchCalendarEventBotSync: async () => {
          set(
            { isCalendarEventBotSyncLoading: true },
            false,
            "settings/fetchCalendarEventBotSync/request"
          );

          try {
            const response = await getCalendarSyncSettingStatus();
            set(
              {
                calendarEventBotSync: response.data.calendar_sync_enabled,
                isCalendarEventBotSyncLoading: false,
              },
              false,
              "settings/fetchCalendarEventBotSync/success"
            );
          } catch {
            set(
              { isCalendarEventBotSyncLoading: false },
              false,
              "settings/fetchCalendarEventBotSync/error"
            );
          }
        },

        updateCalendarEventBotSync: async (enabled) => {
          const previousValue = useSettingsStore.getState().calendarEventBotSync;

          set(
            {
              calendarEventBotSync: enabled,
              isCalendarEventBotSyncSaving: true,
            },
            false,
            "settings/updateCalendarEventBotSync/request"
          );

          try {
            const response = await updateCalendarSyncSetting({ enabled });
            set(
              {
                calendarEventBotSync: response.data.calendar_sync_enabled,
                isCalendarEventBotSyncSaving: false,
              },
              false,
              "settings/updateCalendarEventBotSync/success"
            );
          } catch {
            set(
              {
                calendarEventBotSync: previousValue,
                isCalendarEventBotSyncSaving: false,
              },
              false,
              "settings/updateCalendarEventBotSync/error"
            );
          }
        },
      }),
      {
        name: "iih-ai-note-taker-settings",
        partialize: (state) => ({
          language: state.language,
          speakerIdentification: state.speakerIdentification,
          autoGenerateSummary: state.autoGenerateSummary,
          notifyOnComplete: state.notifyOnComplete,
          notifyOnSummary: state.notifyOnSummary,
          notifyActionItems: state.notifyActionItems,
          summaryModel: state.summaryModel,
          openAiKeySet: state.openAiKeySet,
        }),
      }
    ),
    { name: "SettingsStore" }
  )
);
