import { useMyFetch } from '#imports'
import type {
  GenericResponse,
  GenericResponseChildren,
  GenericResponseItems,
} from '~/types'
import type { Product } from '~/types/product'

export const useProductStore = defineStore('productStore', () => {
  const { $toast } = useNuxtApp()
  const productList = ref<Product[]>()
  const modules = ref()

  const checkoutStore = useCheckoutStore()

  async function getList(count: number, categoryId = 1) {
    try {
      const { data } = await useMyFetch<GenericResponseItems<[]>>(
        `/api/public/products/category/${categoryId}?p=1&elems=${count}`,
        {
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: async (_, status) => {
            // await navigateTo("/error", { replace: true });
            throw createError({
              statusCode: status,
              statusMessage: `HTTP error: ${status}`,
            })
          },
        },
      )

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

  async function getModules() {
    try {
      const { data } = await useMyFetch<GenericResponseChildren<[]>>(
        `/api/public/module/e_shop`,
        {
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      modules.value = data.children.find(
        (item: { id: number, name: string }) =>
          item.name === 'currency_rates_bar',
      )
    }
    catch (error) {
      console.error('getList error:', error)
    }
  }

  async function incrementCartItem(id: number) {
    try {
      const res = await useMyFetch<GenericResponse<object>>(
        `/api/public/user/cart/item/add/${id}/1`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      if (res.status === 200) {
        $toast.success('Item successfully added to your cart.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
        await checkoutStore.getUserCart()
      }
      else {
        $toast.error('Failed to add item to cart. Please try again.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
      }
    }
    catch (error) {
      $toast.error('An unexpected error occurred while updating your cart.', {
        autoClose: 5000,
        dangerouslyHTMLString: true,
      })
      console.error('incrementCartItem error:', error)
    }
  }

  async function decrementCartItem(id: number) {
    try {
      const res = await useMyFetch<GenericResponse<object>>(
        `/api/public/user/cart/item/subtract/${id}/1`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      if (res.status === 200) {
        $toast.success('Item successfully removed from your cart.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
        await checkoutStore.getUserCart()
      }
      else {
        $toast.error('Failed to removed item from cart. Please try again.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
      }
    }
    catch (error) {
      $toast.error('An unexpected error occurred while updating your cart.', {
        autoClose: 5000,
        dangerouslyHTMLString: true,
      })
      console.error('decrementCartItem error:', error)
    }
  }

  async function deleteCartItem(id: number) {
    try {
      const res = await useMyFetch<GenericResponse<object>>(
        `/api/public/user/cart/item/${id}`,
        {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      if (res.status === 200) {
        $toast.success('Item successfully removed from your cart.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
        await checkoutStore.getUserCart()
      }
      else {
        $toast.error('Failed to removed item from cart. Please try again.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
      }
    }
    catch (error) {
      $toast.error('An unexpected error occurred while updating your cart.', {
        autoClose: 5000,
        dangerouslyHTMLString: true,
      })
      console.error('deleteCartItem error:', error)
    }
  }

  return {
    productList,
    modules,
    getList,
    getModules,
    incrementCartItem,
    decrementCartItem,
    deleteCartItem,
  }
})
