import { ref } from 'vue'
import { defineStore } from 'pinia'
import { adminService } from '../services/adminService'
import { useThemeStore } from './theme'
import type { AdminSettings, QuickCallEntry } from '../types/models'

const DEFAULT_SETTINGS: AdminSettings = {
  id: 0,
  updated_at: null,
  logo_base64: null,
  logo_mime_type: null,
  company_name: 'Auburn Oil',
  link_facebook: null,
  link_google: null,
  link_website: null,
  link_google_review: null,
  quick_calls: null,
  show_automatics: true,
  show_stats: true,
  show_service: true,
  show_ticker: true,
  default_theme: 'dark',
}

export const useSettingsStore = defineStore('settings', () => {
  const settings = ref<AdminSettings>({ ...DEFAULT_SETTINGS })
  const loaded = ref(false)

  function parseQuickCalls(): QuickCallEntry[] {
    if (!settings.value.quick_calls) return []
    try {
      return JSON.parse(settings.value.quick_calls) as QuickCallEntry[]
    } catch {
      return []
    }
  }

  function logoDataUrl(): string | null {
    if (settings.value.logo_base64 && settings.value.logo_mime_type) {
      return `data:${settings.value.logo_mime_type};base64,${settings.value.logo_base64}`
    }
    return null
  }

  async function fetchSettings() {
    try {
      const response = await adminService.settings.get()
      if (response.data?.settings) {
        settings.value = response.data.settings
        loaded.value = true
        // Re-init theme with server default for users without a localStorage preference
        const themeStore = useThemeStore()
        themeStore.initTheme(settings.value.default_theme)
      }
    } catch {
      console.error('Failed to fetch admin settings')
    }
  }

  async function updateSettings(data: Partial<AdminSettings>) {
    const response = await adminService.settings.update(data as Record<string, unknown>)
    if (response.data?.settings) {
      settings.value = response.data.settings
    }
    return response
  }

  async function uploadLogo(file: File) {
    const response = await adminService.settings.uploadLogo(file)
    if (response.data?.settings) {
      settings.value = response.data.settings
    }
    return response
  }

  async function deleteLogo() {
    const response = await adminService.settings.deleteLogo()
    if (response.data?.settings) {
      settings.value = response.data.settings
    }
    return response
  }

  return {
    settings,
    loaded,
    parseQuickCalls,
    logoDataUrl,
    fetchSettings,
    updateSettings,
    uploadLogo,
    deleteLogo,
  }
})
