// resources/js/stores/programStore.js
import api from '@/api/axios'
import {
  overrideProgram as apiOverrideProgram,
  createProgram,
  deleteProgram,
  fetchPrograms,
  getProgramUpdatePreview,
  getProgramResetPreview,
  getProgram,
  reorderPrograms,
  translateProgramsApi,
  updateProgram
} from '@/api/programApi'
import { defineStore } from 'pinia'
import {
  createFormDataWithFile,
  extractErrorMessage,
  extractResponseData,
  getSlugConflictPayload,
  removeItemFromArray,
  showToast,
  updateItemInArray
} from '../composables/useStoreHelpers'
import { createCacheManager } from '../utils/cacheManager'

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

export const useProgramStore = defineStore('programs', {
  state: () => ({
    programs: [],
    total: 0,
    loading: false,
    saving: false,
    deleting: false,
    reordering: false,
    isLoadingUpdatePreview: false,
    isLoadingResetPreview: false,
    error: null,
    selectedProgram: null,
    language: null
  }),

  actions: {
    async fetchProgramsLazy({ page = 1, rows = 10, sortField = '', sortOrder = '', search = '', language } = {}) {
      const resolvedLanguage = language || this.language || undefined
      const cacheKey = cacheManager.generateKey({ page, rows, sortField, sortOrder, search, language: resolvedLanguage })
      
      // ✅ Check cache first
      const cachedData = cacheManager.load(cacheKey)
      if (cachedData) {
        this.programs = cachedData.data || []
        this.total = cachedData.total || 0
        return {
          success: true,
          fromCache: true,
          data: {
            data: this.programs,
            total: this.total
          }
        }
      }

      this.loading = true
      this.error = null
      try {
        const response = await fetchPrograms({
          page,
          per_page: rows,
          sort_by: sortField,
          sort_order: sortOrder,
          search,
          language: resolvedLanguage,
        })
        const payload = response.data.data || response.data
        
        // Handle pagination
        if (payload.data && Array.isArray(payload.data)) {
          this.programs = payload.data
          this.total = payload.total
        } else if (Array.isArray(payload)) {
          this.programs = payload
          this.total = payload.length
        } else {
          this.programs = []
          this.total = 0
        }

        // Save to cache
        cacheManager.save(cacheKey, {
          data: this.programs,
          total: this.total
        })
        cacheManager.clearExpired()
        this.language = resolvedLanguage || null

        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        this.programs = []
        this.total = 0
        showToast('error', 'Error', this.error)
        throw err
      } finally {
        this.loading = false
      }
    },

  // In programStore.js
async createProgram(data) {
  this.saving = true
  this.error = null
  try {
    let response
    
    // Check if we have a file to upload
    if (data.header_image_file && data.header_image_file instanceof File) {
      const formData = createFormDataWithFile(data, 'header_image', data.header_image_file)
      response = await api.post('admin/programs/add', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
    } else {
      // No file upload, send as regular JSON
      const { header_image_file, ...cleanData } = data
      response = await createProgram(cleanData)
    }
    
    const newProgram = extractResponseData(response)
    if (Array.isArray(this.programs)) {
      this.programs.unshift(newProgram)
      this.total++
    }
    
    cacheManager.clearAll()
    const successMessage = response?.data?.message || 'Program created successfully'
    showToast('success', 'Success', successMessage)
    
    return response
  } catch (err) {
    if (getSlugConflictPayload(err)) {
      throw err
    }
    this.error = extractErrorMessage(err)
    showToast('error', 'Error', this.error)
    throw err
  } finally {
    this.saving = false
  }
},

async updateProgram(id, data) {
  this.saving = true
  this.error = null
  try {
    let response
    
    if (data.header_image_file && data.header_image_file instanceof File) {
      const formData = createFormDataWithFile(data, 'header_image', data.header_image_file)
      formData.append('_method', 'PUT') // Laravel method spoofing for file uploads
      
      response = await api.post(`admin/programs/${id}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
    } else {
      const { header_image_file, ...cleanData } = data
      response = await updateProgram(id, cleanData)
    }
    
    const updated = extractResponseData(response)
    this.programs = updateItemInArray(this.programs, id, updated)
    if (this.selectedProgram?.id === id) this.selectedProgram = updated
    
    cacheManager.clearAll()
    showToast('success', 'Success', 'Program updated successfully')
    
    return response
  } catch (err) {
    this.error = extractErrorMessage(err)
    showToast('error', 'Error', this.error)
    throw err
  } finally {
    this.saving = false
  }
},


    async deleteProgram(id, params = {}) {
      this.deleting = true
      this.error = null
      try {
        const response = await deleteProgram(id, params)
        if (!params?.language || params.language === 'en') {
          this.programs = removeItemFromArray(this.programs, id)
          this.total--
          if (this.selectedProgram?.id === id) this.selectedProgram = null
        }
        
        cacheManager.clearAll()
        const successMessage =
          response?.data?.message || response?.message || 'Program deleted successfully'
        showToast('success', 'Deleted', successMessage)
        
        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        showToast('error', 'Error', this.error)
        throw err
      } finally {
        this.deleting = false
      }
    },
    // Override a global program for current franchise
    async overrideProgram(id, data) {
      this.saving = true
      this.error = null
      try {
        let response
        if (data.header_image_file && data.header_image_file instanceof File) {
          const formData = createFormDataWithFile(data, 'header_image', data.header_image_file)
          response = await api.post(`admin/programs/${id}/override`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          })
        } else {
          response = await apiOverrideProgram(id, data)
        }
        
        cacheManager.clearAll()
        showToast('success', 'Success', 'Program overridden successfully')
        
        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        showToast('error', 'Error', this.error)
        throw err
      } finally {
        this.saving = false
      }
    },

    async adoptGlobalTranslation(id, language = 'en') {
      this.saving = true
      try {
        const response = await api.post(`admin/programs/${id}/adopt-global`, { language })
        cacheManager.clearAll()
        return response
      } finally {
        this.saving = false
      }
    },

    async resetProgramToGlobal(id, language = 'en') {
      this.saving = true
      try {
        const response = await api.post(`admin/programs/${id}/reset-global`, { language })
        cacheManager.clearAll()
        return response
      } finally {
        this.saving = false
      }
    },

    async updateProgramToLatestGlobal(id, language = 'en') {
      this.saving = true
      try {
        const response = await api.post(`admin/programs/${id}/update-latest-global`, { language })
        cacheManager.clearAll()
        return response
      } finally {
        this.saving = false
      }
    },

    async fetchUpdatePreview(programId, language = 'en') {
      this.isLoadingUpdatePreview = true
      this.error = null
      try {
        const response = await getProgramUpdatePreview(programId, language)
        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        throw err
      } finally {
        this.isLoadingUpdatePreview = false
      }
    },

    async fetchResetPreview(programId, language = 'en') {
      this.isLoadingResetPreview = true
      this.error = null
      try {
        const response = await getProgramResetPreview(programId, language)
        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        throw err
      } finally {
        this.isLoadingResetPreview = false
      }
    },

    async getProgram(id, params = {}) {
      this.loading = true
      this.error = null
      try {
        const response = await getProgram(id, params)
        this.selectedProgram = extractResponseData(response)
        return response
      } catch (err) {
        this.error = extractErrorMessage(err)
        showToast('error', 'Error', this.error)
        throw err
      } finally {
        this.loading = false
      }
    },
 async reorderPrograms(programs) {
      this.reordering = true
      this.error = null

      // Optimistic: show the new order instantly (like the old drag table),
      // keep a backup so we can revert if the save fails.
      const previous = this.programs
      this.programs = programs

      try {
        // Create payload with id and order_no for each program
        const payload = {
          programs: programs.map((program, index) => ({
            id: program.id,
            order_no: index + 1
          }))
        }

        const response = await reorderPrograms(payload)

        cacheManager.clearAll()
        showToast('success', 'Updated', 'Programs reordered successfully')

        return response
      } catch (err) {
        this.programs = previous // revert on failure
        this.error = extractErrorMessage(err)
        showToast('error', 'Error', this.error)
        throw err
      } finally {
        this.reordering = false
      }
    },

    // ✅ NEW: Translate programs
    async translatePrograms(payload) {
      this.saving = true
      try {
        const response = await translateProgramsApi(payload)
        const data = extractResponseData(response)
        cacheManager.clearAll()
        return { success: true, data }
      } catch (err) {
        const error = extractErrorMessage(err)
        return { success: false, error }
      } finally {
        this.saving = false
      }
    },

  },

getters: {
  isBusy: (state) => state.loading || state.saving || state.deleting || state.reordering || state.isLoadingUpdatePreview, // ✅ include preview loading
  hasError: (state) => !!state.error
}

})
