import { useMyFetch } from '#imports'
import type {
  componentsListType,
  GenericResponse,
  PlanPrediction,
} from '~/types'
import type { FrontPageSection } from '~/types/frontSection'
import type { MinMaxRange } from '~/types/planPrediction'

export const useStore = defineStore('store', () => {
  const currentPageID = ref('')

  // calculator
  const monthlySavings = ref(137)
  const storagePeriod = ref(10)
  const totalInvestment: Ref<number> = ref(0)
  const minMaxRange = ref({} as MinMaxRange)

  const components = ref({} as FrontPageSection[])

  const getSections = async (id: string) => {
    const { data } = await useMyFetch<GenericResponse<FrontPageSection[]>>(
      `/api/public/front/sections/${id}`,
    )
    components.value = data
  }

  async function getComponents(): Promise<componentsListType[]> {
    try {
      const children = components.value

      if (!children || !Array.isArray(children)) {
        console.warn('No components available in store.')
        return []
      }

      const componentsList = [] as componentsListType[]

      for (const child of children) {
        const componentName = child.front_section.component_name
        if (!componentName) continue

        try {
          const componentInstance = (
            await import(`@/components/section/${componentName}.vue`)
          ).default

          const nonReactiveComponent = markRaw(componentInstance)
          componentsList.push({
            name: componentName,
            component: child.front_section,
            componentInstance: nonReactiveComponent,
          })
        }
        catch (error) {
          console.error(`Failed to load component ${componentName}`, error)
        }
      }
      return componentsList
    }
    catch (error) {
      console.error('Failed to process components list', error)
    }
    return []
  }

  async function getCalculator() {
    try {
      const { data } = await useMyFetch<GenericResponse<PlanPrediction>>(
        `/api/public/plan-prediction/easy/calculate?monthly_deposit=${monthlySavings.value}&years=${storagePeriod.value}`,
        {
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      totalInvestment.value = data.total_investement_value
    }
    catch (error) {
      console.error('getList error:', error)
    }
  }

  async function getMinMaxRange() {
    try {
      const { data } = await useMyFetch<GenericResponse<MinMaxRange>>(
        '/api/public/front/minmaxinvestment',
        {
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      minMaxRange.value = data
    }
    catch (error) {
      console.error('getList error:', error)
    }
  }

  const getMinAmount = computed(() => {
    return Math.ceil(minMaxRange.value.min)
  })
  const getMaxAmount = computed(() => {
    return Math.ceil(minMaxRange.value.max)
  })

  return {
    currentPageID,
    components,
    totalInvestment,
    monthlySavings,
    storagePeriod,
    minMaxRange,
    getCalculator,
    getComponents,
    getSections,
    getMinMaxRange,
    getMinAmount,
    getMaxAmount,
  }
})
