import { activitiesAPI, translateActivitiesApi } from '@/api/activities'
import { defineStore } from 'pinia'

import { createCacheManager } from '../utils/cacheManager'

// 🔥 CACHE CONFIGURATION
const cacheManager = createCacheManager('activities', 10 * 60 * 1000) // 10 minutes

export const useActivityStore = defineStore('activity', {
  state: () => ({
    activities: [],
    total: 0,
    loading: false,
    saving: false,
    deleting: false,
    reordering: false,
    isLoadingUpdatePreview: false,
    isLoadingResetPreview: false,
    selectedActivity: null,
    currentPage: 1,
    rowsPerPage: 10,
    searchTerm: '',
    sortField: '',
    sortOrder: 0,
    language: null, // ✅ NEW: Language filter
  }),

  getters: {
    isLoading: (state) =>
      state.loading ||
      state.saving ||
      state.deleting ||
      state.reordering ||
      state.isLoadingUpdatePreview ||
      state.isLoadingResetPreview,
  },

  actions: {
    /**
     * Fetch activities with pagination, search, and sorting
     */
    async fetchActivitiesLazy(params = {}) {
      this.loading = true
      try {
        const response = await activitiesAPI.getAll({
          page: params.page || this.currentPage,
          rows: params.rows || this.rowsPerPage,
          search: params.search || this.searchTerm,
          sortField: params.sortField || this.sortField,
          sortOrder: params.sortOrder !== undefined ? params.sortOrder : this.sortOrder,
          language: params.language || this.language || undefined,
        })

        // Parse activities and handle cta_button JSON string
        const activities = (response.data?.data || []).map(activity => ({
          ...activity,
          cta_button: typeof activity.cta_button === 'string' 
            ? JSON.parse(activity.cta_button || '{}')
            : activity.cta_button
        }))

        this.activities = activities
        this.total = response.data?.total || 0
        this.loading = false
        return response
      } catch (error) {
        this.loading = false
        console.error('Error fetching activities:', error)
        throw error
      }
    },

    /**
     * Fetch activity by ID
     */
    async fetchActivityById(id, params = {}) {
      this.loading = true
      try {
        const response = await activitiesAPI.getById(id, params)
        
        // Parse cta_button if JSON string
        const activity = {
          ...response.data,
          cta_button: typeof response.data.cta_button === 'string' 
            ? JSON.parse(response.data.cta_button || '{}')
            : response.data.cta_button
        }
        
        this.selectedActivity = activity
        this.loading = false
        return response
      } catch (error) {
        this.loading = false
        console.error('Error fetching activity:', error)
        throw error
      }
    },

    /**
     * Create new activity
     */
    async createActivity(data) {
      this.saving = true
      try {
        const response = await activitiesAPI.create(data)
        this.saving = false
        
        // Reload activities from first page
        await this.fetchActivitiesLazy({ page: 1 })
        
        return response
      } catch (error) {
        this.saving = false
        console.error('Error creating activity:', error)
        throw error
      }
    },

    /**
     * Update existing activity
     */
    async updateActivity(id, data, options = {}) {
      this.saving = true
      try {
        const response = await activitiesAPI.update(id, data)
        this.saving = false
        
        // Reload activities only when explicitly requested by caller
        if (options.reloadList) {
          await this.fetchActivitiesLazy()
        }
        
        return response
      } catch (error) {
        this.saving = false
        console.error('Error updating activity:', error)
        throw error
      }
    },

    /**
     * Delete activity
     */
    async deleteActivity(id, options = {}) {
      this.deleting = true
      try {
        const response = await activitiesAPI.delete(id, options.params || {})
        this.deleting = false
        
        // Reload activities only when explicitly requested by caller
        if (options.reloadList) {
          await this.fetchActivitiesLazy()
        }
        
        return response
      } catch (error) {
        this.deleting = false
        console.error('Error deleting activity:', error)
        throw error
      }
    },

    /**
     * Reorder activities
     */
    async reorderActivities(activities) {
      this.reordering = true

      // Optimistic: show the new order instantly; revert if the save fails.
      const previous = this.activities
      this.activities = activities

      try {
        const response = await activitiesAPI.reorder(activities)
        this.reordering = false
        return response
      } catch (error) {
        this.activities = previous // revert on failure
        this.reordering = false
        console.error('Error reordering activities:', error)
        throw error
      }
    },

    async adoptGlobalTranslation(id, language = 'en') {
      this.saving = true
      try {
        const response = await activitiesAPI.adoptGlobal(id, language)
        return response
      } finally {
        this.saving = false
      }
    },

    async resetActivityToGlobal(id, language = 'en') {
      this.saving = true
      try {
        const response = await activitiesAPI.resetToGlobal(id, language)
        return response
      } finally {
        this.saving = false
      }
    },

    async updateActivityToLatestGlobal(id, language = 'en') {
      this.saving = true
      try {
        const response = await activitiesAPI.updateToLatestGlobal(id, language)
        return response
      } finally {
        this.saving = false
      }
    },

    async fetchUpdatePreview(id, language = 'en') {
      this.isLoadingUpdatePreview = true
      try {
        const response = await activitiesAPI.getUpdatePreview(id, language)
        return response
      } finally {
        this.isLoadingUpdatePreview = false
      }
    },

    async fetchResetPreview(id, language = 'en') {
      this.isLoadingResetPreview = true
      try {
        const response = await activitiesAPI.getResetPreview(id, language)
        return response
      } finally {
        this.isLoadingResetPreview = false
      }
    },

    /**
     * Update pagination parameters and reload
     */
    updatePaginationParams(params) {
      if (params.page !== undefined) this.currentPage = params.page
      if (params.rows !== undefined) this.rowsPerPage = params.rows
      if (params.search !== undefined) this.searchTerm = params.search
      if (params.sortField !== undefined) this.sortField = params.sortField
      if (params.sortOrder !== undefined) this.sortOrder = params.sortOrder
      if (params.language !== undefined) this.language = params.language
    },

    /**
     * Translate multiple activities
     */
    async translateActivities(payload) {
      this.saving = true
      try {
        const response = await translateActivitiesApi(payload)
        const apiResponse = response.data
        
        if (apiResponse?.status === true || apiResponse?.success) {
          cacheManager.clearAll() // Ensure cache is cleared after translation
          return {
            success: true,
            data: apiResponse.data,
          }
        } else {
          return {
            success: false,
            error: apiResponse?.message || 'Failed to translate activities'
          }
        }
      } catch (error) {
        return {
          success: false,
          error: error.response?.data?.message || error.message || 'Translation failed'
        }
      } finally {
        this.saving = false
      }
    },

    /**
     * Set selected activity
     */
    setSelectedActivity(activity) {
      this.selectedActivity = activity
    },

    /**
     * Clear selected activity
     */
    clearSelectedActivity() {
      this.selectedActivity = null
    }
  }
})
