import type { GenericResponse } from '~/types'
import type { Customer } from '~/types/user'

export const useUserStore = defineStore('userStore', () => {
  const store = useStore()
  const menuStore = useMenuStore()
  const checkoutStore = useCheckoutStore()

  const { $toast } = useNuxtApp()

  const fullUserData = ref<Customer | null>(null)
  const isLogged = ref<boolean>(true)
  const user = ref<string | null>(null)

  async function checkIsLogged() {
    try {
      const { data } = await useMyFetch<GenericResponse<Customer>>(
        `/api/public/user`,
        {
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: async (_, status) => {
            throw createError({
              statusCode: status,
              statusMessage: `HTTP error: ${status}`,
            })
          },
        },
      )

      if ('loggedin' in data && data.loggedin === true) {
        isLogged.value = true
        user.value = `${data.first_name} ${data.last_name}` as string
        fullUserData.value = data
        checkoutStore.accountPhoneNumber = fullUserData.value.phone_number
      }
      else {
        isLogged.value = false
        user.value = null
        fullUserData.value = null
      }
    }
    catch (error) {
      console.error('checkIsLogged error:', error)
    }
  }

  // login
  const email = ref()
  const password = ref()
  const vLogin = ref<boolean>(true)
  const vCodeVerify = ref<boolean>(false)
  const vCode = ref<number | null>(null)
  async function logIn() {
    try {
      const data = await useMyFetch<GenericResponse<object>>(
        `/api/public/user/session/start`,
        {
          method: 'POST',
          body: JSON.stringify({
            mail: email.value,
            password: password.value,
          }),
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      if (data.status === 200 || data.status === 201) {
        console.log(vCodeVerify.value)

        $toast.success('Code successfully sent to your email', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
        vLogin.value = false
        vCodeVerify.value = true
      }
      else {
        $toast.error('Failed to sent code to your email. Please try again.', {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
      }

      store.minValue = data
    }
    catch (error) {
      console.error('getList error:', error)
    }
  }

  const sendFormCode = async (redirect?: boolean) => {
    try {
      await useMyFetch<GenericResponse<object>>(
        `/api/public/user/session/confirm`,
        {
          method: 'POST',
          body: JSON.stringify({
            code: vCode.value,
            mail: email.value,
          }),
          headers: {
            'Content-Type': 'application/json',
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`)
          },
        },
      )

      await checkIsLogged()

      if (isLogged.value) {
        if (redirect) {
          console.log(isLogged.value)
          menuStore.navigateToItem()
        }
        else {
          // window.location.href = atob(redirect);
        }
      }
      else {
        useNuxtApp().$toast.error(`Error occurred: Failed to confirm code`, {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        })
      }
    }
    catch (e) {
      console.error(e)
      useNuxtApp().$toast.error(`Invalid code provided`, {
        autoClose: 5000,
        dangerouslyHTMLString: true,
      })
    }
  }

  return {
    isLogged,
    user,
    fullUserData,
    vCodeVerify,
    vCode,
    email,
    password,
    logIn,
    checkIsLogged,
    sendFormCode,
  }
})
