import { reactive, computed, readonly } from 'vue'
import * as authService from '../services/auth.js'
import * as userProfileService from '../services/userProfile.js'
import * as lifeEventService from '../services/lifeEvent.js'
import * as epicScriptService from '../services/epicScript.js'
import * as lifePathService from '../services/lifePath.js'

const state = reactive({
  isLoggedIn: false,
  isLoading: false,
  currentStep: 1,
  userInfo: null,
  userProfile: null,
  events: [],
  scripts: [],
  paths: [],
  currentPath: null,
  registrationData: {
    nickname: '',
    gender: '',
    mbti: '',
    zodiac: '',
    profession: '',
    hobbies: [],
    childhood: { date: '', text: '' },
    joy: { date: '', text: '' },
    low: { date: '', text: '' },
    future: { vision: '', ideal: '' }
  }
})

const hasProfile = computed(() => {
  return state.userProfile && state.userProfile.nickname
})

const login = async (phone, smsCode) => {
  state.isLoading = true
  try {
    const res = await authService.login({ phone, smsCode })
    state.isLoggedIn = true
    await fetchUserProfile()
    return { success: true, hasProfile: hasProfile.value }
  } catch (error) {
    return { success: false, error: error.message }
  } finally {
    state.isLoading = false
  }
}

const logout = async () => {
  await authService.logout()
  state.isLoggedIn = false
  state.userInfo = null
  state.userProfile = null
}

const fetchUserProfile = async () => {
  try {
    const res = await userProfileService.getCurrentProfile()
    if (res.data) {
      state.userProfile = userProfileService.transformToFrontendFormat(res.data)
      Object.assign(state.registrationData, state.userProfile)
    }
    return res.data
  } catch (error) {
    return null
  }
}

const saveUserProfile = async () => {
  state.isLoading = true
  try {
    const dataToSave = { ...state.registrationData }
    if (state.userProfile?.id) {
      await userProfileService.updateProfile({
        id: state.userProfile.id,
        ...dataToSave
      })
    } else {
      await userProfileService.createProfile(dataToSave)
    }
    await fetchUserProfile()
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  } finally {
    state.isLoading = false
  }
}

const updateRegistration = (data) => {
  Object.assign(state.registrationData, data)
}

const setCurrentStep = (step) => {
  state.currentStep = step
}

const fetchEvents = async () => {
  try {
    const res = await lifeEventService.getEventList()
    state.events = lifeEventService.transformListToFrontend(res.data || [])
    return state.events
  } catch (error) {
    return []
  }
}

const createEvent = async (eventData) => {
  try {
    await lifeEventService.createEvent(eventData)
    await fetchEvents()
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
}

const fetchScripts = async () => {
  try {
    const res = await epicScriptService.getScriptList()
    state.scripts = epicScriptService.transformListToFrontend(res.data || [])
    return state.scripts
  } catch (error) {
    return []
  }
}

const createScript = async (scriptData) => {
  try {
    await epicScriptService.createScript(scriptData)
    await fetchScripts()
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
}

const selectScript = async (id) => {
  try {
    await epicScriptService.selectScript(id)
    await fetchScripts()
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
}

const fetchPaths = async () => {
  try {
    const res = await lifePathService.getPathList()
    state.paths = lifePathService.transformListToFrontend(res.data || [])
    return state.paths
  } catch (error) {
    return []
  }
}

const setCurrentPath = (path) => {
  state.currentPath = path
}

const initialize = async () => {
  const token = uni.getStorageSync('access_token')
  if (token) {
    state.isLoggedIn = true
    await fetchUserProfile()
  }
}

export const useAppStore = () => {
  return readonly({
    ...state,
    hasProfile,
    login,
    logout,
    fetchUserProfile,
    saveUserProfile,
    updateRegistration,
    setCurrentStep,
    fetchEvents,
    createEvent,
    fetchScripts,
    createScript,
    selectScript,
    fetchPaths,
    setCurrentPath,
    initialize
  })
}

export default useAppStore
