import { api } from 'boot/axios'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface FontSizeResponse {
  fontSize: number
}

interface FontSizeError {
  message: string
  code: number
}

export const useTextSizeStore = defineStore('textSize', () => {
  // State
  const baseSize = ref<number>(16) // Значение по умолчанию
  const isLoading = ref<boolean>(false)
  const error = ref<FontSizeError | null>(null)
  const isInitialized = ref<boolean>(false)

  // Константы
  const minFontSize = 12
  const maxFontSize = 20
  const fontSizeStep = 2

  // Getters
  const currentFontSize = computed(() => baseSize.value)
  const canIncrease = computed(() => baseSize.value < maxFontSize)
  const canDecrease = computed(() => baseSize.value > minFontSize)

  // Actions
  const fetchFontSize = async () => {
    try {
      isLoading.value = true
      const response = await api.get<FontSizeResponse>('customer/settings')
      baseSize.value = clampFontSize(response.data.fontSize)
      updateCssVariable()
    } catch (err) {
      handleError(err, 'Failed to fetch font size')
      baseSize.value = 16 // Fallback к значению по умолчанию
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const updateFontSize = async (newSize: number) => {
    try {
      const validatedSize = clampFontSize(newSize)
      
      await api.put('customer/settings', { fontSize: validatedSize })
      
      baseSize.value = validatedSize
      updateCssVariable()
      error.value = null
    } catch (err) {
      handleError(err, 'Failed to update font size')
      throw err
    }
  }

  const increaseFontSize = async () => {
    if (!canIncrease.value) return
    await updateFontSize(baseSize.value + fontSizeStep)
  }

  const decreaseFontSize = async () => {
    if (!canDecrease.value) return
    await updateFontSize(baseSize.value - fontSizeStep)
  }

  // Helpers
  const clampFontSize = (size: number): number => {
    return Math.max(minFontSize, Math.min(size, maxFontSize))
  }

  const updateCssVariable = () => {
    document.documentElement.style.setProperty(
      '--dynamic-font-size',
      `${baseSize.value}px`
    )
  }

  const handleError = (err: unknown, defaultMessage: string) => {
    const apiError = err as { response?: { data: { message: string; code: number } } }
    error.value = {
      message: apiError?.response?.data?.message || defaultMessage,
      code: apiError?.response?.data?.code || 500
    }
    console.error('FontSize Error:', error.value)
  }

  // Инициализация при первом использовании
  const initialize = async () => {
    if (isInitialized.value) return
    
    try {
      await fetchFontSize()
    } catch {
      // Оставляем значение по умолчанию
    } finally {
      isInitialized.value = true
    }
  }

  return {
    baseSize,
    currentFontSize,
    minFontSize,
    maxFontSize,
    isLoading,
    error,
    canIncrease,
    canDecrease,
    fetchFontSize,
    increaseFontSize,
    decreaseFontSize,
    updateFontSize,
    initialize
  }
})